Azure AD Series – 2: Integrating Azure active directory authentication with a single page application (SPA)

In my last post, I discussed in general regarding centralised identity access management and azure active directory. In this post, I will dig a little deeper and start with how to integrate AAD-based authentication in a single-page application. The first step is to register an application as shown in the previous post.

Fortunately, you don’t have to start from scratch and Microsoft provides good QuickStart templates which can be used for different kind of applications.

Select the application which you registered and click on the ‘Quickstart’ option on the left side.Choose ‘Single-page application (SPA)’ option.
Select your desired platform and follow the pre-requisite steps mentioned (this includes setting up redirect URI in step 1).

For the sake of this post lets select ‘React’.

Once you open the code you would see lot of files.The code uses MSAL (Microsoft authentication library for JavaScript) which is the official library provided by Microsoft  for authenticating users with Azure AD.The file which we are interested in is called authConfig.js. This will have all the configurations specific to your active directory tenant already configured.

ClientId : This is Application / client ID you can get from the overview page of your app registration

Authority: Value of authority is a combination of values and it also depends on the supported account types selected during registration. Refer to this documentation to get the right URL for authority.

Redirect URI : These are the authorised redirect URIs specified for your registered application. These will usually be multiple i.e. for each different environment . The current one with the localhost is the one for your local setup.

The above code creates configuration object which needs to be passed to MSAL library PublicClientApplication .

Next code snippet in authConfig.js file is of scope.

Scopes are permissions you are asking the user the consent to during sign-in.In this case, we are connecting to Microsoft graph API and asking for user profile information and that is what is mentioned in the scopes array i.e. User.Read. When you connect to your own APIs you can create scopes in the app registration of API and then mention it here so that you can ask access for a specific piece of information. We will see that flow in the upcoming posts.

Lastly replace the graphMeEndpoint with the correct URL .

Now you can run the application and play around with sign in.

Your SPA application is integrated with AD authentication and can be used as a starter for any project.

Do checkout this pluralsight skills paths having various courses covering end to end all the aspects of azure active directory integration.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.