Published Date: 13 May 2022
This is a technical article directed at developers who are working with Azure Active Directory (AD) to secure a Web API whilst integrating it with a React front end. This article aims to describe the process and steps required to allow a Web API to be protected by the Authentication Services provided by Azure and Azure AD. It uses a frontend app for the user to consume the endpoints, both protected and unprotected.
Azure Architecture
-
1 Create the Azure Architecture
Azure provides a comprehensive out of the box authentication package, which works with several different types of end-user applications. In this article we will be using a B2C tenant to allow the users to integrate with the protected and unprotected endpoints provided by an API that you will also need to manage. This can be utilised in role management and for the security of sensitive data.
The first step to achieve the above is to create a B2C Tenant – these next steps are described well in the available Microsoft documentation:
Step 1a – Create a B2C Tenant
https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-tenantStep 1b – Create AD Tenant
https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-register-applications
Step 1c – Create Necessary User flows
The next part of the article will only focus on the sign-up and sign-in user flow, with self -service password reset.
Step 1d – Optional Step – Integrate with extra identity providers
Azure AD provides various options to integrate with other identity providers such as: Google Accounts, Microsoft Accounts, Facebook accounts and many more. The link below will take you through how you can add one or more identity providers.
https://docs.microsoft.com/en-us/azure/active-directory-b2c/add-identity-provider
-
2 Create API Project and Download Packages
Step 2 – Create API Project locally in Visual Studio
Now we need to create the API that you will be securing, it does not need to have your desired endpoints now for the protection to be active. Feel free to use the starter endpoint provided or add your own. You should create a project file wherever you wish to store this, in your source control or local directory.
Step 2a – Create Project and Download Packages
You then create a local API project selecting ASP.NET Core Web API in the project template in Visual Studio, leaving all configurations as default.
To be able to authenticate using Azure AD you will need to download NuGet packages listed here:Microsoft.Identity.Web
Microsoft.AspNetCore.Authentication.JwtBearer
Step 2b – Adding to Config and Startup.cs
We then add to appsettings.json the following code to the left.
Once added, in your controllers you can now can add [Authorise] above where the route is called to mean that this endpoint is now protected by the AD that has been set up.
"AzureAdB2C": {
"Instance": "https://<tenant-name>.b2clogin.com/",
"ClientId": "<clientId>",
"Domain": "<tenant-name>.onmicrosoft.com ",
"SignUpSignInPolicyId": "<sign-up-sign-in-policy-name>"
},
Next, we add to startup.cs:
This is placed in the Configure method above the UseAuthorization call.
app.UseAuthentication();
Next in the Startup method we add a call to config that we have just created in appsettings.json.
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
Configuration.Bind("AzureAdB2C", options);
-
3 Create Web API application in Azure
You now need to create the Azure instance of your Web API in Azure so you can make calls to it from your frontend app.
Follow these steps to create an API Registration:
Step 3a:
Go to your AD B2C Tenant and select ‘App Registrations’ and select ‘new registration’ from the top menu.
Step 3b:
Call the app something obvious such as ‘webapi1’ – you should allow accounts in any identity provider or organisation and leave both access and id tokens blank as this Web API will not be returning them.Step 3c:
Once this has been created go to the ‘Expose an API’ section from the left-hand menu. This is where you will create a ‘scope’ for your API.Step 3d:
First set the Application ID URI, this should be set to something easy to remember and recognise such as https://<tenant -name>.onmicrosoft.com/apiStep 3e:
Now you can create a scope, you will have to reference this again so make a note of the full-length URL of the scope. Tip: give the scope a name and description to help differentiate it from others you may create in the future.Step 3f:
Go to your originally created webapp and go to ‘API Permissions’ again on the left-hand menu, to add the scope you have just created in the Web API.Step 3g:
Select ‘add a permission’ then select ‘My APIs’ from the next menu. Then select the Web API you have just created and check the permission that you have also just created.Step 3h:
Once you have added the permission, you need to grant consent for access to the newly added permission. You do this by selecting the button marked ‘Grant admin consent for <tenant-name>’ and you will see a green check mark appear next to the newly added permission. -
4 Create React Login App
You now need to create a React App using the create-react-app function where a blank starter app will be created with a homepage and initial config.
Step 4a – Adding the required NPM Packages
We can now install the NPM packages for the app. These are the two packages that you will need to add, details on how to add them to your project are in the following links:
https://www.npmjs.com/package/react-azure-b2c
https://www.npmjs.com/package/jwt-decodeStep 4b – Add Authentication Config
Now we need to add our authentication credentials to the app, this is done by adding the code on the right into the index.js file this is located in the src directory.
Step 4c – Create authentication.js file
You will need to create an authentication file call it auth.js, this acts as an interface within your app to call login and logout endpoints, as well as getting information about the user that is provided by Azure AD in a token.
The file needs to contain this code:
import authentication from 'react-azure-b2c';
import decodeJWT from 'jwt-decode';
class Auth {
isLoggedIn() {
if (authentication.getAccessToken()) {
return true;
}
return false;
};
logout() {
authentication.signOut();
};
getToken() {
return authentication.getAccessToken();
};
currentUser() {
const token = authentication.getAccessToken();
const decoded = decodeJWT(token.accessToken);
return {
decoded
};
};
}
export default Auth;
authentication.initialize({
instance: 'https://login.microsoftonline.com/tfp/',
tenant: '<tenant-name>.onmicrosoft.com',
signInPolicy: '<sign-up-sign-in-policy-name',
applicationId: '<client-id>',
clientId: '<client-id>',
cacheLocation: 'sessionStorage',
scopes: ['https://<tenant-name>.onmicrosoft.com/api/<scope-name>'],
redirectUri: 'http://localhost:3000',
postLogoutRedirectUri: window.location.origin,
});
Now in app.js you should change how the app initialises, this is shown below.
authentication.run(() => {
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
});
-
5 Create Your endpoints
Finally, your app will run, and it will require you to login before you can view the basic pages that are provided in the stater app.
Now you can create endpoints in your API project and add the authorise attribute to them, these will be available from your frontend app, and they will work as expected.
Summary
Following these steps will leave you with a secure Web API that uses Azure Active Directory B2C React Client App Authorisation. I‑Finity are able to offer their customers support with Azure Hosting and services.
There is also documentation provided about using both authorised and unauthorised areas of your front-end app, this will allow you to test whether the protected endpoints are in fact only allowing the authenticated users to access your API. This is discussed on the react-azure-b2c NPM package page: https://www.npmjs.com/package/react-azure-b2c