Click here to share this article on LinkedIn »

I found many ways to implement Azure AD authentication using React and a .NET Core 2.x backend. In this article, I will demonstrate how to implement this type of authentication.

Register your application

The first step is to register your Azure AD. Once you’ve done that, you can use the keys generated by Azure to implement authentication in your app.

Now, we will configure the frontend to get an Azure AD access token and then to consume this token in the backend.

If you want to see the code in details, please check the following repository: https://github.com/Odonno/azuread-react-dotnet-core-example

The frontend

There is plenty of implementation for the frontend and the most used is surely the angular-adal library, not really the best choice in our case. We could use the simple adal.js but why having to reinvent the wheel everytime?

Fortunately, I found a library on GitHub called react-adal that seems to make a pretty good job. So, let’s start with it and see how simple it is.

npm install react-adal

Once you get there you’ll need to write two things:

a config file with the keys you got from Azure in the previous step

call the authenticate method

Once you got your configuration file completed, execute this function in your index.jsx file:

And you are ready to go. Now, each time a user enter in this function, a new page will be displayed so he can set his credentials and connect. And as a bonus, I give you the getToken() method to easily get the authentication token we will need to ensure the user has access to our backend.

Remember to set your headers as is to make your HTTP calls with the Azure AD authentication token.

One thing to note is that the first token you generate from the callback url has a 1 hour lifetime. So, when this token is near expiration, a refresh token will be retrieved by the library. By default, the react-adal library will try to refreh the token at least 5 minutes before the current token expiration date.

The backend

Now, everytime the user send a request to your backend, you need to ensure the token is valid one. And this token will also help you to detect who is the user.

The configuration file

You will have to set this information in your appsettings.json according to your keys.

Configure services

Start adding a few line of code in the ConfigureServices() method.

And make sure you have this line of code in your Configure() method.

Oh, and if you use a Swagger generator, here is the code to add the Authorization token form in Swagger.

Detect user profile

Well now, your backend is secure but how do we know who is logged in.

Here are some basic methods you can use in your application:

Conclusion

And voila, you are good to go.