GBG Developers

Guides   |   A Step-by-Step Guide using Microsoft Azure

A Step-by-Step Guide using Microsoft Azure

Creating an Azure account and username

If your business already uses Microsoft Azure and you already have a username that you wish to use for GBG API authorization, you can skip the steps here. Otherwise, create a free or pay-as-you-go account at https://account.azure.com/organization (a credit card may be required). Once you’ve done that, your browser will automatically be at the Azure Portal (portal.azure.com).

Azure Portal (portal.azure.com)

The left-side palette provides access to the Azure Active Directory. Click on that, and then select Users to create a username if desired (or you can use the initial username that the portal will display).

Adding Users

Obtaining the URL for the identity provider's authentication service

The OAuth 2.0 OpenID Connect URL is a piece of information that GBG requires to set up your API access. Within the Azure portal it is easy to find this URL. Click on Azure Active Directory->App registrations->Endpoints to find a list of URLs.

Obtaining the URL for the Identity Provider's Authentication Service

Search for OpenID Connect metadata document and make a note of that URL to supply to GBG. It will be in a format like:

Example OpenID Connect Metadata Document URL:
https://login.microsoftonline.com/aa1122aa-aab1-1122-1212-12221aaabb1a/v2.0/.well-known/openid-configuration

Incidentally the long chain of characters in the URL are a tenant identifier in the Azure cloud. Other service providers will use different identifier formats, but the URL will end in /.well-known/openid-configuration.

Now that you have obtained this URL, you can send it to GBG to enable Identity Solution API access!

Creating an application

If you already have an application that you wish to integrate with GBG Identity Solution, you can skip this section. The example here uses Azure App Service which provides a fully managed platform so that you can concentrate on the end application instead of the infrastructure and middleware.

In the left pane in the Azure portal (portal.azure.com) click on App Services and then click through to add a new service. You may need to create a Resource Group; if so, assign it any name and continue. Pick an application name suitable for your business and note that Azure will append it with .azurewebsites.net for start-ups, or with the organization’s domain name if Azure is already configured for this. Choose the desired software language for developing the application (such as Python, PHP or Node.JS).

In this example, Node.JS was selected, which is a JavaScript engine that executes on a server; it allows JavaScript to be used as a general-purpose programming language.

Application configuration summary

 

After you have clicked through and created the application, after a short while the Azure portal will indicate that the deployment was successful. In the example below, the application name was sales-team-central.azurewebsites.net.

Application successfully deployed

 

You should now be able to browse to the app website, and see a default message indicating that the managed platform is running.

Default web page for the application

Application configuration

Follow the four application configuration items listed here.

  1. Enabling Authentication for your Application

    In order for the identity provider (Microsoft) to be able to successfully accept user credentials and return an access token, your application needs to be added to Azure Active Directory. The aim is to obtain an application identifier (also known as a client identifier in OAuth 2.0) that can be sent as part of the authentication and authorization process.

    Applications can be added by going to the Azure portal (portal.azure.com) and selectingAzure Active Directory -> App registrations -> New registration.



    Registering the application in Azure Active Directory

    Once the application is registered, you can click on the application name to see the application identifier, also known as the client identifier when used with OAuth procedures.

    The procedures require the identity provider’s single sign-on page to be able to redirect the user back to your application. The desired URL for this needs to be enabled by clicking on Add a Redirect URI as shown in the screenshot below (note that you’ll also be later clicking on Add an Application ID URI to expose an API. This is described in the next section).



    Adding the Redirect URL for OAuth and exposing an (application) API

    As an example, if your application identifier is sales-team-central.azurewebsites.net  then a suitable redirect URI could be https://sales-team-central.azurewebsites.net/oauth2callback  (the text oauth2callback  could be replaced with anything else that you prefer).

    Before you click Save, scroll down and enableAccess tokens, ID tokens  and set the indicated toggle in the screenshot below to Yes.



    Redirect URL configuration

    By the end of this step, the OAuth 2.0 OpenID Connect service is enabled for authentication, however the actual permissions that will be authorized need to be defined, by exposing an API for your web application. It is required as part of the authentication and authorization process for the identity provider (Microsoft) to provide an access token with permission for using a web API. This is described next.

  2. Exposing Application APIs
    The identity provider’s access token needs to contain a scope field that indicates what permissions are being granted in the token. To create this scope field within the Azure portal, navigate to Azure Active Directory->App registrations. Alongside the application name there is you application (client) identifier. Make a note of it (copy-paste it into Notepad for example) because it will be used in a later step. In this example, the application (client) identifier was d4fad300-421e-48f7-9dae-d48a5b0c9abd.

    Click on the application name. Next, click on Add an Application ID URI and accept the suggested URI that the portal will auto-generate. In the screen that appears, click on Add a Scope.

    You can give the scope any name, but it is suggested to use the style shown in the screenshot below. Click through to Add scope.

    Adding a scope to an application API

    Click on Add a client application, and paste in the application (client) identifier that was copied in the step above. Check the scope that was created too.

    Adding the client (application) identifier to the application API

    By the end of these steps, you should see the scope created, and the application URI added to the authorized applications list.

    Summary screen showing the exposed API configuration

  3. Creating an Application Password (Client Secret)
    You’re almost there! This is the penultimate step for getting the Microsoft Azure service to provide an access token. For machine-to-machine scenarios at least one client secret needs to be created (and if you’re unsure and may wish to consider M2M scenarios in future, then you can still continue with this section, otherwise you can skip to the next step). Within the Azure portal, navigate back to Azure Active Directory->App registrations and then click on the application name. Click on Certificates and Secrets and then select New client secret. Click through to complete this task.

    Creating an Application Password (Client Secret)

  4. Setting the Access Token Version
    The access token that is generated by Microsoft Azure has a version number. It needs to be set to 2. In the Azure portal, click on Azure Active Directory -> App registrations and then select the application. Click on Manifest as shown in the screenshot below, and edit the accessTokenAcceptedVersion line in order to set it to 2.

    Setting the Access Token Version

    Once the modification is saved, all steps are complete! The Azure account and the application have been configured for providing an access token in a format usable for allowing the GBG platform to provide a GBG access token for Identity Solution API use.

    The next section describes how the authentication and authorization can be tested using some sample code.

Creating a redirect handler application

Note: You can skip this section for M2M applications.

To recap the authentication and authorization process, it is expected for the user application to send a HTTP GET message to the identity provider in order to retrieve an authentication code. That authentication code is then exchanged (using HTTP POST) for an access token from the identity provider. Finally, that access token is exchanged for another access token, this time from GBG. That final access token provides access to the Identity Solution APIs.

In order to test that authentication and authorization is functioning, HTTP GET and HTTP post requests can be sent using a web browser and the Postman application.

However, the authentication process involves the Azure OpenID Connect service trying to redirect to a page named /oath2callback (this was configured in the section Enabling Authentication for your Application). If there is no such web page, there will be a short delay before the authorization occurs.

You can skip this section if you don’t mind the delay while testing, or if you already have a web server application that you can configure to handle the redirect.

This section describes a trivial test application that will accept HTTP requests to the /oauth2callback URL, for the purposes of allowing the identity provider to send an authorization code that will be exchanged for an identity provider access token. Ensure that you have Node.js and NPM (visit https://nodejs.org/en/ to obtain these) installed on your PC if you wish to try to build this test application. The commands shown here can be entered using Windows PowerShell.

You’ll also need Microsoft Visual Code (free software available from https://code.visualstudio.com/). Within Visual Code there are three important icons in the left side activity bar. The first one brings up an Explorer pane on the left side, in order to access local folders of interest (the application will be initially created locally on your PC). The blocks icon allows for extensions to be installed within Visual Code. Click that to install the Azure extension (which will appear as the third icon highlighted in the screenshot below). Once you click the blocks icon, a text box will appear where you can type Azure in order to reduce the number of visible hits. Locate Azure App Service and Azure Account, and install both of them.

Installing Azure Extensions to Visual Studio Code

Create a folder anywhere on your PC, called development.

Using Windows PowerShell type the following to install some libraries globally (these will be used to implement the web server):

Installing Node.JS libraries for implementing a web server:
npm install -g express
npm install -g express-generator
npm install –g pug

From inside the development folder, type the following to create a skeleton web server application:

Creating a skeleton web application:
express sales-team-central --view pug

The command will have created a sales-team-central folder containing the skeleton app. Some of the code resides in a file called app.js, however each web page has its associated JavaScript file in the routes subfolder. There is a shorthand representation of the HTML code for each web page in the views subfolder. By exploring these folders you’ll notice that the skeleton app already has code for index and users web pages.

In the sales-team-central folder, type the following to install any dependencies:

Installing Application Dependencies:
npm install

The aim of the test code will be to create an oauth2callback page so that when the single sign-on occurs, a redirection can occur to the page.

In order to achieve this, edit the app.js file (using Visual Code if desired; click the left side icon to view the Explorer pane, and then click on File -> Open Folder and locate the sales-team-central folder) to include the following two lines at the appropriate places:

Modifications to app.js:
var cbRouter = require('./routes/oauth2callback');
app.use('/oauth2callback', cbRouter);

Next, in the routes subfolder, copy the existing users.js file, and name it oauth2callback.js.
Edit the newly created file. In the router.get function insert the following code:

Modifications to oauth2callback.js router.get function:
var code_field_content = req.query.code;
res.render('oauth2callback', { title: 'Getting Started', code: code_field_content });

In the views subfolder, copy the existing index.pug file, name it oauth2callback.pug and then edit it. The file contains a shorthand form of HTML. Append the following content, indented to match the last line in that file (note: the indentation must use spaces for indents rather than tabs, if the rest of the file uses spaces; tabs can only be used if the entire file uses tabs):

Modification to oauth2callback.pug file (Observe the indent using spaces!):
  p IDP authorization code is #{code}

You’re now ready to test the code, initially on your PC. Type the following to run the code locally:

Running the application locally:
npm start

In a web browser navigate to http://localhost:3000 and you should see a default welcome page for the skeleton code. Now try visiting http://localhost:3000/oauth2callback?code=ABCDE

You should see a welcome page indicating the received code. Once you’re happy with the code, it can be uploaded to Azure. Type Ctrl-C to stop the web server and get back to the command prompt.

To upload the code, make sure that it is available in the left side Explorer pane within Visual Code (click on the left side Explorer icon and then go to File -> Open Folder to select the sales-team-central folder).

Click on the Azure icon on the left side, and add your account. Once you see your account type (such as Pay-As-You-Go in the screenshot below) click on the blue up-arrow just above it. This will bring up a prompt to select the code folder that you wish to upload. Select sales-team-central, and the prompt will change to select the target application name in Azure. Select sales-team-central again. If a prompt appears, confirm that you wish to deploy the code. The upload will take about a minute.

Uploading your application to Azure using Visual Studio Code' Azure Extension

The application will automatically run! You can now test it by visiting the application URL:

Testing the Example Application Redirect URL Handler:
https://sales-team-central.azurewebsites.net/oauth2callback?code=ABCDE

If you see the Getting Started web page appear, then you’re ready to test the authentication and authorization procedure! To do that, check out the Testing Authorization and APIs using Postman section of this guide.

 

APPENDIX: AZURE APPLICATION MANIFEST EXAMPLE

Azure’s Application Manifest contains a formatted (JSON format) representation of the application configuration. An example manifest is shown here for reference.

{
	"id": "67810dda-950e-4350-abe9-109f50751e1e",
	"acceptMappedClaims": null,
	"accessTokenAcceptedVersion": 2,
	"addIns": [],
	"allowPublicClient": true,
	"appId": "d4fad300-421e-48f7-9dae-d48a5b0c9abd",
	"appRoles": [],
	"oauth2AllowUrlPathMatching": false,
	"createdDateTime": "2019-10-10T16:50:34Z",
	"groupMembershipClaims": null,
	"identifierUris": [
		"api://d4fad300-421e-48f7-9dae-d48a5b0c9abd"
	],
	"informationalUrls": {
		"termsOfService": null,
		"support": null,
		"privacy": null,
		"marketing": null
	},
	"keyCredentials": [],
	"knownClientApplications": [],
	"logoUrl": null,
	"logoutUrl": null,
	"name": "sales-team-central",
	"oauth2AllowIdTokenImplicitFlow": true,
	"oauth2AllowImplicitFlow": true,
	"oauth2Permissions": [
		{
			"adminConsentDescription": "Allow access for Users",
			"adminConsentDisplayName": "Access for Users",
			"id": "61bef314-d03b-4747-b065-0cda64d1a002",
			"isEnabled": true,
			"lang": null,
			"origin": "Application",
			"type": "User",
			"userConsentDescription": "Allow access for Users",
			"userConsentDisplayName": "Access for Users",
			"value": "UserScope.All"
		}
	],
	"oauth2RequirePostResponse": false,
	"optionalClaims": null,
	"orgRestrictions": [],
	"parentalControlSettings": {
		"countriesBlockedForMinors": [],
		"legalAgeGroupRule": "Allow"
	},
	"passwordCredentials": [
		{
			"customKeyIdentifier": null,
			"endDate": "2020-10-14T09:41:32.181Z",
			"keyId": "2a4e64bf-ebad-476c-9214-3f970cc712f2",
			"startDate": "2019-10-14T09:43:41.426Z",
			"value": null,
			"createdOn": "2019-10-14T09:43:42.0071567Z",
			"hint": "xJH",
			"displayName": "App password (client secret) 1"
		}
	],
	"preAuthorizedApplications": [
		{
			"appId": "d4fad300-421e-48f7-9dae-d48a5b0c9abd",
			"permissionIds": [
				"61bef314-d03b-4747-b065-0cda64d1a002"
			]
		}
	],
	"publisherDomain": "centralservices1.onmicrosoft.com",
	"replyUrlsWithType": [
		{
			"url": "https://sales-team-central.azurewebsites.net/oauth2callback",
			"type": "Web"
		}
	],
	"requiredResourceAccess": [
		{
			"resourceAppId": "00000003-0000-0000-c000-000000000000",
			"resourceAccess": [
				{
					"id": "e1fe6dd8-ba31-4d61-89e7-88639da4683d",
					"type": "Scope"
				}
			]
		}
	],
	"samlMetadataUrl": null,
	"signInUrl": null,
	"signInAudience": "AzureADMyOrg",
	"tags": [],
	"tokenEncryptionKeyId": null
}