1. Authentication

Implementing single sign-on with Azure AD B2C IDP

OpenID Connect is a powerful feature that enables you to provide single sign-on capabilities for any identity provider that supports the specification. In this tutorial we'll walk you step by step through what you'll need to get single sign-on working by using Azure AD B2C as the identity provider. By the end of this tutorial, you'll be able to sign in via Azure and be logged into OrderCloud.

Implementation outcome

Before we start, let's understand the finished product. By the end of this tutorial you will have a locally running application that will redirect you to Azure's sign-in page and after successfully signing in you should see your login details including:

  • Currently authenticated user
  • OrderCloud Access Token
  • OrderCloud Refresh Token (if configured)
  • Azure ID Token (if configured)

Marketplace configuration

First, you need to access your Marketplace in the Sitecore Cloud Portal.

After accessing, take special note of the OrderCloud Base API URL, which identifies the base URL needed for all API requests.

For this demonstration we are on the Sandbox environment in the region Us-West so our base API URL is https://sandboxapi.ordercloud.io, yours may look different.

Supporting entities

We will be creating a single-sign-on experience for buyer users specifically, so we'll create the most basic OrderCloud entities required to support that scenario.

Create a buyer organization

http
POST sandboxapi.ordercloud.io/v1/buyers HTTP/1.1
Authorization: Bearer INSERT_ACCESS_TOKEN_HERE
Content-Type: application/json; charset=UTF-8

{
  "ID": "buyer1",
  "Name": "Buyer 1",
  "Active": true
}
javascript
import { Tokens, Buyers } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
Buyers.Create({
  ID: "buyer1",
  Name: "Buyer 1",
  Active: true
})
.then(response => {
  console.log(response);
})
.catch(err => console.log(err));
typescript
import { Tokens, Buyers, Buyer, OrderCloudError } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
const buyer: Buyer = await Buyers.Create({
  ID: "buyer1",
  Name: "Buyer 1",
  Active: true
})
.catch((err:OrderCloudError) => console.log(err));
console.log(buyer);
csharp
using OrderCloud.SDK;

var client = new OrderCloudClient(...);
Buyer response = await client.Buyers.CreateAsync(new Buyer {
  ID = "buyer1",
  Name = "Buyer 1",
  Active = true
});

Security profile

http
POST https://sandboxapi.ordercloud.io/v1/securityprofiles HTTP/1.1
Authorization: Bearer INSERT_ACCESS_TOKEN_HERE
Content-Type: application/json; charset=UTF-8
{
  "ID": "buyerProfile",
  "Name": "Buyer Security Profile",
  "Roles": [
    "Shopper"
  ]
}
javascript
import { Tokens, SecurityProfiles } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
SecurityProfiles.Create({
  ID: "buyerProfile",
  Name: "Buyer Security Profile",
  Roles: ["Shopper"]
})
.then(response => {
  console.log(response);
})
.catch(err => console.log(err));
typescript
import { Tokens, SecurityProfiles, SecurityProfile, OrderCloudError } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
const securityProfile: SecurityProfile = await SecurityProfiles.Create({
  ID: "buyerProfile",
  Name: "Buyer Security Profile",
  Roles: ["Shopper"]
})
.catch((err:OrderCloudError) => console.log(err));
console.log(securityProfile);
csharp
using OrderCloud.SDK;

var client = new OrderCloudClient(...);
await client.AuthenticateAsync();
SecurityProfile response = await client.SecurityProfiles.CreateAsync(new SecurityProfile {
  ID = "buyerProfile",
  Name = "Buyer Security Profile",
  Roles = new ApiRole[] { ApiRole.Shopper }
});

Security profile assignment

http
POST https://sandboxapi.ordercloud.io/v1/securityprofiles/assignments HTTP/1.1
Authorization: Bearer INSERT_ACCESS_TOKEN_HERE
Content-Type: application/json; charset=UTF-8

{
  "SecurityProfileID": "buyerProfile",
  "BuyerID": "buyer1"
}
javascript
import { Tokens, SecurityProfiles } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
SecurityProfiles.SaveAssignment({
  SecurityProfileID: "buyerProfile",
  BuyerID: "buyer1"
})
.then(() => {
  // no response when security profile assigned
})
.catch(err => console.log(err));
typescript
import { Tokens, SecurityProfiles, OrderCloudError } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
await SecurityProfiles.SaveAssignment({
  SecurityProfileID: "buyerProfile",
  BuyerID: "buyer1"
})
.catch((err:OrderCloudError) => console.log(err));
csharp
using OrderCloud.SDK;

var client = new OrderCloudClient(...);
await client.AuthenticateAsync();
await client.SecurityProfiles.SaveAssignmentAsync(new SecurityProfileAssignment {
  SecurityProfileID = "buyerProfile",
  BuyerID = "buyer1"
});

API client

http
POST https://sandboxapi.ordercloud.io/v1/apiclients HTTP/1.1
Authorization: Bearer INSERT_ACCESS_TOKEN_HERE
Content-Type: application/json; charset=UTF-8

{
  "AccessTokenDuration": 600,
  "Active": true,
  "AppName": "Buyer Client",
  "RefreshTokenDuration": 43200,
  "AllowAnyBuyer": true,
  "AllowSeller": true
}
javascript
import { Tokens, ApiClients } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
ApiClients.Create({
  AccessTokenDuration: 600,
  Active: true,
  AppName: "Buyer Client",
  RefreshTokenDuration: 43200,
  AllowAnyBuyer: true,
  AllowSeller: true
})
.then((response) => {
  console.log(response);
})
.catch(err => console.log(err));
typescript
import { Tokens, ApiClients, ApiClient, OrderCloudError } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
const apiClient: ApiClient = await ApiClients.Create({
  AccessTokenDuration: 600,
  Active: true,
  AppName: "Buyer Client",
  RefreshTokenDuration: 43200,
  AllowAnyBuyer: true,
  AllowSeller: true
})
.catch((err:OrderCloudError) => console.log(err));
console.log(apiClient);
csharp
using OrderCloud.SDK;

var client = new OrderCloudClient(...);
await client.AuthenticateAsync();
ApiClient response = await client.ApiClients.Create(new ApiClient {
  AccessTokenDuration = 600,
  Active = true,
  AppName = "Buyer Client",
  RefreshTokenDuration = 43200,
  AllowAnyBuyer = true,
  AllowSeller = true
});

Record the ID from the response for OpenID Connect configuration.

Configuring OIDC (OpenID Connect) via OrderCloud

Configure Azure

Create an Azure AD B2C tenant

If you haven't yet, you will need to create a new Azure AD B2C tenant. Follow this tutorial for instructions.

Create a user flow

To keep things simple we're setting up azure with user flows but it will work with custom policies as well. Click on "User Flows"

For demo purposes we used the "Sign in" user flow but you can select whichever one makes sense for you. Any claims selected under "Application Claims" will be encoded into the ID token which is accessible during the /createuser and /syncuser endpoint.

Create an App Registration

Under "App Registrations" click on "New Registration"

Make sure you set Redirect URI to OrderCloud's /ocrpcode endpoint. Please note that the base URL for all OrderCloud endpoints vary by environment/region so make sure to check your marketplace for the correct value.

Under "Overview" of your newly created app registration copy the "Application (client) ID", this will be your ConnectClientID in future steps.

While still under "Overview", click on "Endpoints"

There are two values specifically we are interested in:

  • Azure AD B2C OAuth 2.0 token endpoint (v2) - This will be your TokenEndpoint
  • Azure AD B2C OAuth 2.0 authorization endpoint (v2) - This will be your AuthorizationEndpoint

You should replace <policy-name> with the name of the user flow you created previously.

Next, under "Certificates & secrets" create a new client secret. Copy the generated value, this will be your ConnectClientSecret in future steps.

Start ngrok

You'll need a publicly available endpoint. You can use a tool called ngrok to let us do this locally without having to deploy anything. After installing ngrok run the command ngrok http 3000. This tells ngrok to expose our endpoint (not yet running) on http://localhost:3000 to two public endpoints. After running the command copy either one of those URLs and record it, you'll need it for the next step.

We recommend to keep ngrok running. Restarting it will generate unique public endpoints and require you to update your configuration in OrderCloud.

  1. Create OpenID Connect Integration Event:
http
POST https://sandboxapi.ordercloud.io/v1/integrationEvents HTTP/1.1
Authorization: Bearer INSERT_ACCESS_TOKEN_HERE
Content-Type: application/json; charset=UTF-8

{
  "ID": "openidconnect",
  "Name": "openidconnect",
  "EventType": "OpenIDConnect",
  "CustomImplementationUrl": "{your-ngrok-url}/integration-events",
  "HashKey": "supersecrethash",
  "ElevatedRoles": ["BuyerUserAdmin"]
}
javascript
import { Tokens, IntegrationEvents } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
IntegrationEvents.Create({
  ID: "openidconnect",
  Name: "openidconnect",
  EventType: "OpenIDConnect",
  CustomImplementationUrl: "{your-ngrok-url}/integration-events",
  HashKey: "supersecrethash",
  ElevatedRoles: ["BuyerUserAdmin"]
})
.then(response => {
  console.log(response);
})
.catch(err => console.log(err));
typescript
import { Tokens, IntegrationEvents, IntegrationEvent, OrderCloudError } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
const integrationEvent: IntegrationEvent = await IntegrationEvents.Create({
  ID: "openidconnect",
  Name: "openidconnect",
  EventType: "OpenIDConnect",
  CustomImplementationUrl: "{your-ngrok-url}/integration-events",
  HashKey: "supersecrethash",
  ElevatedRoles: ["BuyerUserAdmin"]
})
.catch((err:OrderCloudError) => console.log(err));
console.log(integrationEvent);
csharp
using OrderCloud.SDK;

var client = new OrderCloudClient(...);
await client.AuthenticateAsync();
IntegrationEvent response = await client.IntegrationEvents.CreateAsync(new IntegrationEvent {
  ID = "openidconnect",
  Name = "openidconnect",
  EventType = IntegrationEventType.OpenIDConnect,
  CustomImplementationUrl = "{your-ngrok-url}/integration-events",
  HashKey = "supersecrethash",
  ElevatedRoles = new ApiRole[] { ApiRole.BuyerUserAdmin }
});
OrderCloud propertyDescription
IDUnique identifier for the integration event
NameA short name describing the integration event, this is not user facing
EventTypeIndicates what type of integration event this is, in our case we should use OpenIDConnect
CustomImplementationUrlThis indicates the base URL of your middleware where OrderCloud should post to. For OpenIDConnect it will call out to the pat /createuser and /syncuser
HashKeyThis is an important security feature that is used by your middleware to validate that requests made to your endpoints are legitimate and come from OrderCloud
ElevatedRolesAn optional array of roles that will be encoded in the user's token and sent along in the payload to /createuser and /syncuser. In our case we are defining BuyerUserAdmin so that our middleware endpoints have the roles necessary to create users on the fly.
  1. Create OpenID Connect configuration:

HTTP:

http
POST https://sandboxapi.ordercloud.io/v1/openidconnects HTTP/1.1
Authorization: Bearer INSERT_ACCESS_TOKEN_HERE
Content-Type: application/json; charset=UTF-8

{
  "ID": "azure",
  "OrderCloudApiClientID": "CLIENT_ID_FROM_CREATING_API_CLIENT_STEP",
  "ConnectClientID": "CLIENT_ID_FROM_CONFIGURING_AZURE",
  "ConnectClientSecret": "CLIENT_SECRET_FROM_CONFIGURING_AZURE",
  "AppStartUrl": "http://localhost:3000?token={0}&idpToken={1}&refreshToken={3}",
  "AuthorizationEndpoint": "AUTH_ENDPOINT_FROM_AZURE",
  "TokenEndpoint": "TOKEN_ENDPOINT_FROM_AZURE",
  "UrlEncoded": false,
  "CallSyncUserIntegrationEvent": true,
  "IntegrationEventID": "openidconnect",
  "AdditionalIdpScopes": ["CLIENT_ID_FROM_CONFIGURING_AZURE"]
}
javascript
import { Tokens, OpenIdConnects } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
OpenIdConnects.Create({
  ID: "azure",
  OrderCloudApiClientID: "CLIENT_ID_FROM_CREATING_API_CLIENT_STEP",
  ConnectClientID: "CLIENT_ID_FROM_CONFIGURING_AZURE",
  ConnectClientSecret: "CLIENT_SECRET_FROM_CONFIGURING_AZURE",
  AppStartUrl: "http://localhost:3000?token={0}&idpToken={1}&refreshToken={3}",
  AuthorizationEndpoint: "AUTH_ENDPOINT_FROM_AZURE",
  TokenEndpoint: "TOKEN_ENDPOINT_FROM_AZURE",
  UrlEncoded: false,
  CallSyncUserIntegrationEvent: true,
  IntegrationEventID: "openidconnect",
  AdditionalIdpScopes: ["CLIENT_ID_FROM_CONFIGURING_AZURE"]
})
.then(response => {
  console.log(response);
})
.catch(err => console.log(err));
typescript
import { Tokens, OpenIdConnects, OpenIdConnect, OrderCloudError } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
const openIdConnect = await OpenIdConnects.Create({
  ID: "azure",
  OrderCloudApiClientID: "CLIENT_ID_FROM_CREATING_API_CLIENT_STEP",
  ConnectClientID: "CLIENT_ID_FROM_CONFIGURING_AZURE",
  ConnectClientSecret: "CLIENT_SECRET_FROM_CONFIGURING_AZURE",
  AppStartUrl: "http://localhost:3000?token={0}&idpToken={1}&refreshToken={3}",
  AuthorizationEndpoint: "AUTH_ENDPOINT_FROM_AZURE",
  TokenEndpoint: "TOKEN_ENDPOINT_FROM_AZURE",
  UrlEncoded: false,
  CallSyncUserIntegrationEvent: true,
  IntegrationEventID: "openidconnect",
  AdditionalIdpScopes: ["CLIENT_ID_FROM_CONFIGURING_AZURE"]
})
.catch((err:OrderCloudError) => console.log(err));
console.log(openIdConnect);
csharp
using OrderCloud.SDK;

var client = new OrderCloudClient(...);
await client.AuthenticateAsync();
OpenIdConnect response = await client.OpenIdConnects.CreateAsync(new OpenIdConnect {
  ID = "azure",
  OrderCloudApiClientID = "CLIENT_ID_FROM_CREATING_API_CLIENT_STEP",
  ConnectClientID = "CLIENT_ID_FROM_CONFIGURING_AZURE",
  ConnectClientSecret = "CLIENT_SECRET_FROM_CONFIGURING_AZURE",
  AppStartUrl = "http://localhost:3000?token={0}&idpToken={1}&refreshToken={3}",
  AuthorizationEndpoint = "AUTH_ENDPOINT_FROM_AZURE",
  TokenEndpoint = "TOKEN_ENDPOINT_FROM_AZURE",
  UrlEncoded = false,
  CallSyncUserIntegrationEvent = true,
  IntegrationEventID = "openidconnect",
  AdditionalIdpScopes = ["CLIENT_ID_FROM_CONFIGURING_AZURE"]
});

Testing

  1. Clone openidconnect-nextjs
  2. Install dependencies: npm install
  3. Configure environment: Copy .env.example to .env.local
  4. Start server: npm run start
  5. Test: Navigate to http://localhost:3000

Review /createuser and /syncuser endpoints for implementation details.

Troubleshooting

Common issue: "error validating token with authority"

  • Verify configuration values:
    • ConnectClientID
    • ConnectClientSecret
    • OrderCloudClientID
If you have suggestions for improving this article, let us know!