1. Authentication

Implementing single sign-on with Google 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 Google as the identity provider. By the end of this tutorial, you'll be able to sign in via Google and be logged into OrderCloud.

Demo

Before we start, let's take a look at the finished product. Navigate to this website. You will be redirected to Google'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)
  • Google ID Token

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.

Create 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:

http
POST sandboxapi.ordercloud.io/v1/buyers HTTP/1.1
Authorization: Bearer INSERT_ACCESS_TOKEN_HERE
Content-Type: application/json; charset=UTF-8
json
{
  "ID": "buyer1",
  "Name": "Buyer 1",
  "Active": true
}

JavaScript:

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 => {
  // returns the newly created buyer organization
  console.log(response);
})
.catch(err => console.log(err));

TypeScript:

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);

C#:

csharp
using OrderCloud.SDK;

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

Create security profile

HTTP:

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

JavaScript:

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 => {
  // returns the newly created security profile
  console.log(response);
})
.catch(err => console.log(err));

TypeScript:

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);

C#:

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 }
});

Assign security profile

HTTP:

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
json
{
  "SecurityProfileID": "buyerProfile",
  "BuyerID": "buyer1"
}

JavaScript:

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:

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));

C#:

csharp
using OrderCloud.SDK;

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

Create API client

HTTP:

http
POST https://sandboxapi.ordercloud.io/v1/apiclients HTTP/1.1
Authorization: Bearer INSERT_ACCESS_TOKEN_HERE
Content-Type: application/json; charset=UTF-8
json
{
  "AccessTokenDuration": 600,
  "Active": true,
  "AppName": "Buyer Client",
  "RefreshTokenDuration": 43200,
  "AllowAnyBuyer": true,
  "AllowSeller": true
}

JavaScript:

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:

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);

C#:

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 the OpenID Connect configuration.

OpenID Connect configuration

Start ngrok

We'll need a publicly available endpoint. We 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, we'll need when creating a new OpenID Connect

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

Create integration event

HTTP:

http
POST https://sandboxapi.ordercloud.io/v1/integrationEvents HTTP/1.1
Authorization: Bearer INSERT_ACCESS_TOKEN_HERE
Content-Type: application/json; charset=UTF-8
json
{
  "ID": "openidconnect",
  "Name": "openidconnect",
  "EventType": "OpenIDConnect",
  "CustomImplementationUrl": "{your-ngrok-url}/integration-events",
  "HashKey": "supersecrethash",
  "ElevatedRoles": [
    "BuyerUserAdmin"
  ]
}

JavaScript:

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 => {
  // returns the newly created integration event
  console.log(response);
})
.catch(err => console.log(err));

TypeScript:

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);

C#:

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 }
});

Configure Google

Follow Google's instructions for setting up OpenID Connect configuration on their side. You'll need to set the authorized redirect URI to {ordercloud_base_url}/ocrpcode. Take note of the clientID and clientSecret which OrderCloud will refer to as ConnectClientID and ConnectClientSecret respectively, these values will be needed in the following step.

Create a new OpenID Connect

This entity configures the connection between Google and OrderCloud.

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
json
{
  "ID": "google",
  "OrderCloudApiClientID": "CLIENT_ID_FROM_CREATING_API_CLIENT_STEP",
  "ConnectClientID": "GOOGLE_CLIENT_ID_HERE",
  "ConnectClientSecret": "GOOGLE_CLIENT_SECRET_HERE",
  "AppStartUrl": "http://localhost:3000?token={0}&idpToken={1}",
  "AuthorizationEndpoint": "https://accounts.google.com/o/oauth2/v2/auth",
  "TokenEndpoint": "https://oauth2.googleapis.com/token",
  "UrlEncoded": false,
  "CallSyncUserIntegrationEvent": true,
  "IntegrationEventID": "openidconnect",
  "AdditionalIdpScopes": []
}

JavaScript:

javascript
import { Tokens, OpenIdConnects } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
OpenIdConnects.Create({
  ID: "google",
  OrderCloudApiClientID: "CLIENT_ID_FROM_CREATING_API_CLIENT_STEP",
  ConnectClientID: "GOOGLE_CLIENT_ID_HERE",
  ConnectClientSecret: "GOOGLE_CLIENT_SECRET_HERE",
  AppStartUrl: "http://localhost:3000?token={0}&idpToken={1}",
  AuthorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
  TokenEndpoint: "https://oauth2.googleapis.com/token",
  UrlEncoded: false,
  CallSyncUserIntegrationEvent: true,
  IntegrationEventID: "openidconnect",
  AdditionalIdpScopes: []
})
.then(response => {
  // returns the newly created openidconnect
  console.log(response);
})
.catch(err => console.log(err));

TypeScript:

typescript
import { Tokens, OpenIdConnects, OpenIdConnect, OrderCloudError } from "ordercloud-javascript-sdk";

Tokens.Set("INSERT_ACCESS_TOKEN_HERE");
const openIdConnect = await OpenIdConnects.Create({
  ID: "google",
  OrderCloudApiClientID: "CLIENT_ID_FROM_CREATING_API_CLIENT_STEP",
  ConnectClientID: "GOOGLE_CLIENT_ID_HERE",
  ConnectClientSecret: "GOOGLE_CLIENT_SECRET_HERE",
  AppStartUrl: "http://localhost:3000?token={0}&idpToken={1}",
  AuthorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
  TokenEndpoint: "https://oauth2.googleapis.com/token",
  UrlEncoded: false,
  CallSyncUserIntegrationEvent: true,
  IntegrationEventID: "openidconnect",
  AdditionalIdpScopes: []
})
.catch((err:OrderCloudError) => console.log(err));
console.log(openIdConnect);

C.md#:

csharp
using OrderCloud.SDK;

var client = new OrderCloudClient(...);
await client.AuthenticateAsync();
OpenIdConnect response = await client.OpenIdConnects.CreateAsync(new OpenIdConnect {
  ID = "google",
  OrderCloudApiClientID = "CLIENT_ID_FROM_CREATING_API_CLIENT_STEP",
  ConnectClientID = "GOOGLE_CLIENT_ID_HERE",
  ConnectClientSecret = "GOOGLE_CLIENT_SECRET_HERE",
  AppStartUrl = "http://localhost:3000?token={0}&idpToken={1}",
  AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/v2/auth",
  TokenEndpoint = "https://oauth2.googleapis.com/token",
  UrlEncoded = false,
  CallSyncUserIntegrationEvent = true,
  IntegrationEventID = "openidconnect",
  AdditionalIdpScopes = []
});

Testing

OrderCloud and Google should now be completely configured, and you are ready to test to make sure everything is working. To simplify this aspect, we've created a very minimal frontend to test this functionality.

  1. Clone this repository
  2. Install dependencies by running npm install at the root of the project
  3. Copy .env.example to .env.local
  4. Run the project by running npm run start. This will start the server on port 3000. Remember ngrok is already listening to this port and will expose our endpoints publicly.
  5. Navigate to the url http://localhost:3000. If everything is correct you should be redirected to Google's login page. Upon signing in you will be redirected back to the application and should see details about your logged in user

Be sure to look at the /createuser and /syncuser endpoints

Common Issues

Error message: "error validating token with authority"

This issue occurs when OrderCloud attempts to retrieve the ID token from the IDP. This is generally a configuration issue. Confirm ConnectClientID, ConnectClientSecret, and OrderCloudClientID are correct.

If you have suggestions for improving this article, let us know!