Usually when I build a website it’s an ASP.NET Core Razor site created from Visual Studio but I’ve recently started to try to get to grips with the React framework (again within Visual Studio). This means I’m having to relearn a few of the things that I’d previously taken for granted such as authentication.

I usually mange site authentication through Azure AD but it seems the documentation for using this in a React app isn’t quite as fleshed out as that for using it in a Razor app (in which it’s possible to get Visual Studio to scaffold the whole thing for you).

It turns out that this is actually pretty simple to get up and running as there’s a handy (non-Microsoft) NPM package that abstracts away a lot of the hard work, it also has some good documentation on how to get it working though it took a bit of trial and error to figure out.

First off create a new React project in Visual Studio.

Once this has been created add the react-aad-msal package from NPM.

npm install react-aad-msal msal --save

In the src folder create a new javascript file called authProvider.js and copy in the code from the above linked NPM package documentation.

// authProvider.js
import { MsalAuthProvider, LoginType } from 'react-aad-msal';
 
// Msal Configurations
const config = {
  auth: {
    authority: 'https://login.microsoftonline.com/common',
    clientId: '<YOUR APPLICATION ID>',
    redirectUri: '<OPTIONAL REDIRECT URI>'
  },
  cache: {
    cacheLocation: "localStorage",
    storeAuthStateInCookie: true
  }
};
 
// Authentication Parameters
const authenticationParameters = {
  scopes: [
    '<property (i.e. user.read)>',
    'https://<your-tenant-name>.onmicrosoft.com/<your-application-name>/<scope (i.e. demo.read)>'
  ]
}
 
// Options
const options = {
  loginType: LoginType.Popup,
  tokenRefreshUri: window.location.origin + '/auth.html'
}
 
export const authProvider = new MsalAuthProvider(config, authenticationParameters, options)

The main things to note here are that an authority of https://login.microsoftonline.com/common is for multitenant apps, if you want to only allow single tenant authentication this needs to be changed to https://login.microsoftonline.com/{tenantId}, where tenantId is the ID of the tenant your app registration exists in.

For SPL apps like this the redirectUri parameter can just be set to window.location.origin.

If you’re just using this library for site authentication then the only scope you need is user.read, other scopes can be added here but they need to be granted in your app registration as well.

I also changed the loginType to LoginType.Redirect as I find this tends to give a better user experience than popups which are often blocked by the browser.

When creating the app registration this will authenticate against in AAD make sure you add a platform as this will allow you to use implicit flow which can generate authorization and ID tokens which need to be enabled.

To now use authentication in your site just update the index.js file and wrap the App with the new AzureAD provider.

import 'bootstrap/dist/css/bootstrap.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { AzureAD } from 'react-aad-msal';
import { authProvider } from './authProvider';

const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const rootElement = document.getElementById('root');

ReactDOM.render(
  <BrowserRouter basename={baseUrl}>
        <AzureAD provider={authProvider} forceLogin={true}>
            <App />
        </AzureAD>,
  </BrowserRouter>,
  rootElement);

registerServiceWorker();

There’s a good example here which is by the authors of the react-aad-msal package and helps to flesh out the various options available.


OAuth2 Authentication of Azure Functions in React – bitScry · 18th May 2021 at 4:48 pm

[…] Azure Active Directory Authentication for React 6th May 2021 […]

Leave a Reply

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