Click here to Skip to main content
15,063,556 members
Articles / Hosted Services / Azure
Article
Posted 1 Aug 2018

Stats

18.6K views
310 downloads
21 bookmarked

Authentication and Authorization in ASP.NET Core 2.0 using Azure Active Directory and OpenID Connect

Rate me:
Please Sign up or sign in to vote.
5.00/5 (10 votes)
1 Aug 2018CPOL8 min read
This article mainly covers how to setup and configure Azure AD tenant and integrating Azure AD into ASP.NET Core 2.0 web app for authentication and role based authorization.

Introduction

Integrating Azure AD in ASP.NET Core is very simple using the Visual Studio wizard. This article will cover the identity management with Azure AD and related configuration in ASP.NET Core web application. 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.

Coverage Topics

1. 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

2. Integrating Azure AD into ASP.NET Core 2.0 Web Application

  • Choosing template
  • Changes in the appsettings
  • Added extension files for Azure AD authentication
  • Added NuGet packages
  • Setting up Azure AD authentication in startup
  • Applying authorize attribute on the controllers or actions

3. Role Based 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 Drilldown the Basic Shorty

Authentication: It verifies the identity (verifies, who you are).

Authorization: It is a security mechanism which is used to define access permission to do something (verifies, what you can access).

OpenID: It is an authentication mechanism which allows existing account (i.e., Google, Facebook account) to sign in to the websites where you don't need to create specific username and password for each website.

OpenID Connect: It is used for the authentication on 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 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 users to sign-in and authenticate with Azure AD.

1. 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

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.

Image 1

In the create directory page, enter an 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 Create button.

Image 2

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.

Image 3

In the user page, fill-up the Name, User name and Directory role, then create a temporary password for the password field. You will need this temporary password when you log in for the first time 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.

Image 4

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.

Image 5

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 field and click on the Create button on the button of the create page.

Image 6

2. Integrating Azure AD into ASP.NET Core 2.0 Web Application

  • Choosing template
  • Changes in the appsettings
  • Added extension files for Azure AD authentication
  • Added NuGet packages
  • Setting up Azure AD authentication in startup
  • Applying authorize attribute on the controllers or actions

In the Azure AD, we can manually register our applications; but Visual Studio 2017 supports a simple wizard to register 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).

Image 7

Leave the Client Id blank. 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

Image 8

  • 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.

    Image 9

  • 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.

    Image 10

  • 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.

    Image 11

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:

Image 12

Applying Authorize Attribute on the Controllers or Actions

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

Image 13

3. Role Based 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

Did you remember the options of the below 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.

Image 14

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 top action bar and Change "groupMembershipClaims": null to “groupMembershipClaims": "SecurityGroup".

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

Image 15

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.

Image 16

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

Image 17

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.

Image 18

C#
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 top of the controllers or actions according to your requirements.

Image 19

Testing Claims for Role-based Authorization

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

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Habibur Rony
Engineer
United States United States
Lazy software engineer, don’t believe in hard work.

Comments and Discussions

 
QuestionHow to mock this Open ID while Integration testing ? How to generate token while testing ? Pin
sagarsk1530-Oct-18 2:53
Membersagarsk1530-Oct-18 2:53 
How to mock this Open ID while Integration testing ? How to generate token while testing ?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.