In part one, we created a secure web app that can communicate with Azure AD and authenticate users against it. We have also verified that the web app is registered in Azure AD and we tested the login as well.
Behind the scenes
Before taking a look at the code, let’s see what configuration we need to integrate with Azure AD. In our case Visual Studio did all the work for us and retrieved this information and stored it in appsettings.json.
Inside the appsettings.json file of our web app, we can find the domain name that we created before and its TenantId, both of which are unique and identify our AD instance. Also we can see ClientId which uniquely identify our web app. Finally, there is CallbackPath which tells Azure which route to redirect back to once authentication has completed.
Login flow in details
If we go back to the Identity platform diagram, we see that the user is redirected to Azure AD with ClientId, TenantID, callbackPath as redirect_url, and a token. Once the user is authenticated, Azure will respond with id_token or Jwt that we can validate using the app middleware and then give the user an authentication cookie that will keep the user logged in.
All the code that has been generated for us can be found in Startup.cs. Once we open it and check the Configure(…) method we can find that we have app.UseAuthentication() middleware added, which will check each request and use the app service to authenticate users. This service will be configured in the ConfigureServices(…) method, and as we see below Visual Studio has generated this authentication service on line 38 and specified AzureADDefaults schema to be used here. Additionally, the method has passed “options” which has all Azure’s configuration from appsettings.json.
At this point the AddAzureAD service will use OpenId Connect behind the scene to authenticate users and convert the token or Jwt from Azure AD to an auth cookie that will be send to the browser. Finally, we see that this template has a policy defined on line 43, which was added to protect any resource inside our web app.
From part one we saw how easy it was to generate this template and to secure a basic web app without coding it from scratch or spending time on security research as the .NET Identity platform is reliable and up to date. Although there is still some additional code needed to be able to generate a bearer token to secure any API in our web app, but no doubt that this template can be a good boost when starting a web app that services Azure AD users.