> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ownid.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Azure AD B2C

> Azure AD B2C Integration with OwnID

By integrating Azure AD B2C with OwnID, you can implement the full set of OwnID features to streamline your user authentication experience.

## How it Works

Integrate OwnID with Azure AD B2C by completing these four basic steps:

* **Step 1** - Configure your Azure AD B2C tenant.
* **Step 2** - Set up server endpoints using the OwnID npm package.
* **Step 3** - Create an OwnID application in the OwnID Console.
* **Step 4** - Integrate with your frontend.

## Step 1 - Configure Azure AD B2C

### Register an Application for OwnID Integration

You'll need to register a specific application for OwnID integration:

1. In your B2C tenant, navigate to `App registrations`
2. Click `New registration`
3. Fill in the required information:
   * Name: OwnID Integration
   * Supported account types: Accounts in this organizational directory only (default directory only - single tenant)
4. Click `Register`
5. After registration, note down the following values:
   * Application (client) ID
   * Directory (tenant) ID
   * Object ID

<Note> This application will be used specifically for OwnID integration. It's separate from any applications you use for user sign-in flows. </Note>

### Create Client Secret

1. In your registered app, navigate to `Certificates & secrets`
2. Click `New client secret`
3. Add a description and select expiration period
4. Click `Add`
5. **Important**: Note down the client secret value as it will be shown only once

### Configure API Permissions

1. In your registered app, navigate to `API permissions`
2. Click `Add a permission`
3. Select `Microsoft Graph`
4. Select `Application permissions`
5. Add the following permissions:
   * User.ReadWrite.All
6. Click `Add permissions`
7. **Important:** Click `Grant admin consent for [your-tenant-name]` button at the top of the API permissions page. This step is critical - without admin consent, you will get "Insufficient privileges" errors when accessing the Graph API.

### Find Your B2C Extension App ID

Every Azure AD B2C tenant has a special application called the `b2c-extensions-app` that's automatically created:

1. In your B2C tenant, go to `App registrations`
2. Switch to `All applications` if you don't see it immediately
3. Look for `b2c-extensions-app. Do not modify. Used by AADB2C for storing user data.`
4. Note down its Application (client) ID - you'll need this for your environment variables

## Step 2 - Set Up Server Endpoints

For Node.js applications, you can use the official `@ownid/azure-b2c` package which provides all the necessary endpoints:

```bash theme={null}
npm install @ownid/azure-b2c
```

Then, configure your Express application to use the OwnID router:

```javascript theme={null}
// server.js
require('dotenv').config();
const express = require('express');
const { createOwnIdAzureB2CRouter } = require('@ownid/azure-b2c');

const app = express();
const port = process.env.PORT || 3000;

// Required middleware for parsing JSON requests
app.use(express.json());

// Create and mount the OwnID router
const ownidRouter = createOwnIdAzureB2CRouter({
  azureTenantId: process.env.AZURE_TENANT_ID,
  azureClientId: process.env.AZURE_CLIENT_ID,
  azureClientSecret: process.env.AZURE_CLIENT_SECRET,
  azureB2cExtensionAppId: process.env.AZURE_B2C_EXTENSION_APP_ID,
  b2cTenantName: process.env.B2C_TENANT_NAME,
  ownIdSharedSecret: process.env.OWNID_SHARED_SECRET
});

// Mount the router at /ownid
app.use('/ownid', ownidRouter);

// Start the server
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
  console.log(`Endpoints available:`);
  console.log(`  POST http://localhost:${port}/ownid/setOwnIDDataByLoginId`);
  console.log(`  POST http://localhost:${port}/ownid/getOwnIDDataByLoginId`);
  console.log(`  POST http://localhost:${port}/ownid/getSessionByLoginId`);
});
```

You'll need to configure the following environment variables:

```env theme={null}
AZURE_TENANT_ID=your-tenant-id
AZURE_CLIENT_ID=your-client-id
AZURE_CLIENT_SECRET=your-client-secret
AZURE_B2C_EXTENSION_APP_ID=your-extension-app-id
B2C_TENANT_NAME=yourtenant.onmicrosoft.com
OWNID_SHARED_SECRET=your-ownid-shared-secret
```

## Step 3: Create OwnID Application

An OwnID application connects your backend with the OwnID widget in the front end. This OwnID application is assigned a unique `appId` that is then added to the website's front end. To create an OwnID application:

* Open the [OwnID Console](https://console.ownid.com/) and create an account or log in to an existing account.
* Select `Create Application`.
* Define the name of your application, your backend language, and finish the onboarding.

## Step 4 - Integrate with your Frontend

Choose your frontend integration path:

<CardGroup>
  <Card title="OwnID Elite" href="/building-blocks/elite/quickstart">
    Implement the predefined authentication screens provided by OwnID
  </Card>

  <Card title="OwnID Boost" href="/building-blocks/boost/build-login">
    Add OwnID as an add-on to your existing forms
  </Card>
</CardGroup>

## Advanced Usage

### Custom Session Token Generation

If you're using the Node.js package, you can provide your own session token generation logic, such as custom JWT creation:

```javascript theme={null}
const { createOwnIdAzureB2CRouter } = require('@ownid/azure-b2c');
const jwt = require('jsonwebtoken');

// Custom session generator function
const customSessionGenerator = async (userId, email, user) => {
  // Create a custom JWT token
  const token = jwt.sign(
    { 
      sub: userId,
      email: email,
      name: user?.displayName,
      // Add custom claims as needed
    },
    process.env.JWT_SECRET,
    { expiresIn: '1h' }
  );
  
  return {
    accessToken: token,
    expiresIn: 3600,
    tokenType: 'Bearer'
  };
};

// Create router with custom session generator
const ownidRouter = createOwnIdAzureB2CRouter({
  azureTenantId: process.env.AZURE_TENANT_ID,
  azureClientId: process.env.AZURE_CLIENT_ID,
  azureClientSecret: process.env.AZURE_CLIENT_SECRET,
  azureB2cExtensionAppId: process.env.AZURE_B2C_EXTENSION_APP_ID,
  b2cTenantName: process.env.B2C_TENANT_NAME,
  ownIdSharedSecret: process.env.OWNID_SHARED_SECRET,
  customSessionGenerator: customSessionGenerator
});
```

## Next Steps

### Ready to deploy?

<Card title="YES!" href="/building-blocks/pre-deployment-checklist" icon="rocket-launch">
  Take me to the Deployment Checklist
</Card>
