Authentication And Authorization In ASP.NET Core 2.0 Using Azure Active Directory And OpenID Connect

Integrating Azure AD in ASP.NET Core is very simple using Visual Studio wizard. This article will cover the identity management with Azure AD and related configuration in ASP.NET Core web applications. We will check out what's going on behind the scenes to integrate the Azure AD into ASP.NET Core web application for authentication and authorization.

Article Flow -

Setup Azure Active Directory tenant
  • Creating new Azure AD tenant
  • Adding new users in the Azure AD tenant
  • Adding new groups in the Azure AD tenant
  • Registering new application
Integrating Azure AD into ASP.NET Core 2.0 Web Application
  • Choosing template
  • Changes in the app settings
  • Added extension files for Azure AD authentication
  • Added NuGet packages
  • Setting up Azure AD authentication in startup
  • Applying the authorize attribute on controllers or actions
Role Base Authorization in ASP.NET Core 2.0 with OpenID Connect and Azure AD Groups
  • Updating the application manifest file with the Azure AD tenant
  • Getting the group object ID from Azure AD and updating appsettings file
  • Setting up Azure AD authorization in startup
  • Applying policy on the controllers or actions
  • Testing claims for role-based authorization

Prerequisites 

Let's drill down the basics.

  • Authentication
    It verifies the identity (verifies, who you are).
     
  • Authorization
    It is a security mechanism which is used to define the access permission to do something (verifies, what you can access).
     
  • OpenID
    It is an authentication mechanism which allows to use your organizational existing email account (it accesses active directory of your organization) to sign in to the website where you don't need to create specific username and password for that website.
     
  • Open Auth
    It is an authorization mechanism which allows to use existing account (i.e., Google, Facebook account) to sign in and access your profile information to the website and you don't need to create specific username and password for that website.
     
  • OpenID Connect
    It is used for the authentication on the top of the OAuth (provides authorization).
     
  • Azure Active Directory
    It is an identity management service in the cloud for the applications.
     
  • Azure Active Directory tenant
    It is a dedicated instance of an organization within the Azure Directory. It contains the users, groups, register applications and other information and its security. If you don't have the Azure Active Directory tenant then you need to create one before registering and configuring your applications. Finally, it will allow the users to sign-in and authenticate with Azure AD.

Setup Azure Active Directory tenant

Creating New Azure AD Tenant 

Open the Azure Portal account and click on "+ Create a resource" icon in the left pane and filter for the Azure Active Directory. Click on the Create button at the bottom of the page.
 
 

In the "Create directory" page, enter the organization name and Initial domain name. The Initial domain name (say, softdreams; full name: softdreams.onmicrosoft.com) is the Azure Active Directory tenant name. For country or region, choose the country. Finally, click on the "Create" button.
 

Adding New Users in the Azure AD tenant

You need a user before registering your application. To add a user, select the Azure Active Directory>Users>All users>+ New user.

 

In the user page, fill-up the Name, username and directory role, then create a temporary password for the password field. This temporary password will be needed when first time you log in and then, you will need to change it. Finally, click on the Create button.

Adding New Groups in the Azure AD tenant

If you need a role based authentication for your applications then create groups and add users into these groups. To create group, select the Azure Active Directory>Groups>All groups>+ New group. Fill-up the Group type, Group name, Group description and Membership type. Finally click on the Create button at the bottom of the page.
 
 

To add members into the group, select the Azure Active Directory>Groups>All groups. Now find and select the group then select members>+Add members.
 
 

Note
You can synchronize existing users and groups to the Azure AD tenant from on-premises windows Server AD by installing and configuring Azure AD Connect on the server.

Registering New Application

In the example of the .net core project, I didn’t manually register the application. If you want to register a new application manually then select Azure Active Directory>App registration>+ New application registration. Now fill-up the required filed and click on the Create button on the button of the create page.
 

Integrating Azure AD into ASP.NET Core 2.0 Web Application

In Azure AD, we can manually register our applications; but Visual Studio 2017 supports a simple wizard to register a new application and add Azure AD authentication.

Choosing Template

Open Visual Studio to create a new project. Select ASP.NET Core Web Application>Choose Web Application (Model-View-Controller) template> Click on the "Change Authentication" button>Select "Work or School Accounts".

Choose Cloud - Single Organization. Fill up the field of Domain which is the Azure Active Directory tenant name (say, softdreams.onmicrosoft.com).
 
 
Leave blank the Client Id. If you manually register the application in the Azure AD tenant then you will get application ID which is the client Id here. Click on the OK button to create the project. It is now ready to validate the OpenID Connect authentication.
Checking out what's going on behind the scenes, few changes we need to know step by step that happened in the project. 
 
Changes in the Appsettings
 
  • Domain
    This is the Azure Active Directory tenant name (say, softdreams.onmicrosoft.com).
     
  • TenantId
    This is the Azure Active Directory ID. To verify the Directory ID, select Azure Active Directory>Properties>Directory ID.
  • ClientId
    This is the application ID of the web app which is registered automatically by the visual studio wizard. To verify the application ID, select Azure Active Directory>App registrations>find and select your app (say, "HR.AzureAuthentication.HelloWorld")>Application ID
 
  • Callback Path
    This is the redirect path after authentication (say, https://localhost:44387/signin-oidc).
If you open this project and select Solution Explorer>Project properties>Debug, then you will find the SSL enable URL which is https://localhost:44387/.

Now if you want to add the production callback redirect path (say, https://helloworld.softdreams.com/signin-oidc) then select Azure Active Directory>App registrations>find and select your app (say, HR.AzureAuthentication.HelloWorld)>Settings>Reply URLs, then add the production redirect path and save it.
 

Added Extension Files for Azure AD Authentication

The AzureAdAuthenticationBuilderExtensions and AzureAdOptions files are created in the extensions folder.

Added NuGet Packages
  • Microsoft.AspNetCore.Authentication.Cookies and
  • Microsoft.AspNetCore.Authentication.OpenIdConnect are added for authentication.
Setting up Azure AD Authentication in Startup

In the startup file, the below codes are added.
 
 

Applying Authorize Attribute on the Controllers or Actions

In the HomeController file, [Authorize] attribute is added.
 
 

Role Base Authorization in ASP.NET Core 2.0 with OpenID Connect and Azure AD Groups 

Did you remember the options of the bellow image? In this image, we need to check the "Read directory data" if we want to read the AD information of the users like profile, role, groups etc. from the Azure AD.
 

Updating the Application Manifest File with the Azure AD tenant

If you want to read the groups of the user, you need to modify the manifest of the app in Azure AD. To update the manifest file select, Azure Active Directory>App registrations>find and select your app (say, HR.AzureAuthentication.HelloWorld)>Click on the manifest from the top action bar and Change "groupMembershipClaims": null to “groupMembershipClaims": "SecurityGroup".

If you choose “SecurityGroup” then you will get all of the group lists of the users. If you choose “All” then you will get the security groups and distribution lists. Anyway, finally click on the save button.
 
 

Getting the Object ID of the Group from Azure AD and Update Appsettings File

If you want to implement role based authorization then you need the object Id of that group from Azure AD for adding it in the appsettings file. If you add all of the configurations values into the appsettings file then it is easy to modify the values. To get the Object ID of the group, Select, Azure Active Directory>Groups>search your required group>Properties.
 

Now copy the Object ID from the General Setting page and past it into the appsettings.json file of your project.
 

Setting up Azure AD Authorization in Startup

You need to add the below codes into ConfigureServices method of the Startup file. In this project, say, we have two types of roles (admin and user). That's why we are adding Admins and Users groups.
 
services.AddAuthorization(options => {  
    options.AddPolicy("Admins", policyBuilder => policyBuilder.RequireClaim("groups", Configuration.GetValue < string > ("AzureSecurityGroup:AdminObjectId")));  
});  
services.AddAuthorization(options => {  
    options.AddPolicy("Users", policyBuilder => policyBuilder.RequireClaim("groups", Configuration.GetValue < string > ("AzureSecurityGroup:UserObjectId")));  
});  

Applying Policy on the Controllers or Actions

Add the [Authorize(Policy = "Users")] or [Authorize(Policy = "Admins")] attributes on the top of the controllers or actions according to your requirements.

 

Testing Claims for Role-based Authorization

You can check the group list which are coming from the Azure AD after successful login. Use the below codes to do that.

var groups = User.Claims.Where(c => c.Type == "groups").ToList();

Note
Before running the attached project select the appsettings.json file and change the "Domain", "TenantId, "ClientId" "AdminObjectId", "UserObjectId": according to your values of the Azure AD tenant, register application, and groups.