Azure AD Authentication For MVC Web Application

Azure AD is designed for internet scale, Internet-based standards, and protocols and it is not a replacement for on-premises Windows Active Directory.

Before getting into coding and explanations let’s see what are the benefits of using Azure AD over Windows AD.

Windows on Premises AD has limitations: 

  1. Single point of failure. If the domain goes down everything goes down nobody has access to the resources like emails, SharePoint, etc.
  2. Not designed for internet scale.
  3. Too chatty. Any resource you access on your network requires you to keep talking to the domain controller.

Azure AD

  1. Azure AD Identifies Apps, APIs, and Users using internet ready standards
  2. It is designed for internet scale because it supports protocols like OAuth, WS-federation and more.
  3. It is a trust-based architecture, less chatty and there is no single point of failure.
  4. One of the biggest reasons that Azure AD is successful is that it is free.
  5. Azure AD lets you focus on building your application by making it fast and simple to integrate with a world-class identity management solution used by millions of organizations around the world.

     (There are paid versions too that add more value but the freebie version is quite capable)

Now, we have seen the benefits of Azure AD and the differences between the Windows AD and Azure AD. Let’s jump into coding and explanations.

There are two sections in this course:

  1. Setup an MVC web application environment that can support Azure AD Authentication
  2. Creation and Configuration of Azure AD to register the MVC Web Application

Let us get to the actual practice.

Section 1 - Setup an MVC web application environment that can support Azure AD Authentication

Step 1

Open Visual Studio and create an MVC Web Application and make sure that the authentication option is set to “No Authentication” and then hit “OK” as illustrated in the image below.

 Azure AD Authentication

Step 2

Select your project under “Solution Explorer” then you must see the “Project Properties” window. If you don't see it press “F4” key on your keyboard then it will appear.

Change the “SSL Enabled” property value to “True”, then copy the value of “SSL URL” property because you will need it to configure Azure AD.

The image below illustrates the state of “SSL Enabled” property and “SSL URL” property after changing the value of “SSL Enabled” property from “false” to “true”.

 Azure AD Authentication

Step 3

Install all necessary libraries to make our application support Azure AD Authentication.

To install all necessary libraries open “Package Manager Console” to open it, navigate to
Tools > NuGet Package Manager > Package Manager Console

Then install the following packages one by one (copy, paste, and hit enter).

Install-Package Microsoft.Owin
Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.IdentityModel.Protocol.Extensions
Install-Package System.IdentityModel.Tokens.Jwt

Now, let’s do some configuration in “Web.config” xml file

Open your “Web.config” xml file and then copy the xml lines below and paste them inside <appSettings> tag which lives inside <configuration> tag

  1. <add key="ida:ClientId" value="" />  
  2. <add key="ida:Tenant" value=" " />  
  3. <add key="ida:AADInstance" value="https://login.microsoftonline.com/" />  
  4. <add key="ida:PostLogoutRedirectUri" value="https://localhost:44397/" />  

Notice, that the “ida:ClientId” and “ida:Tenant” have empty values because we don’t know their values yet. We will know their values when we register our MVC Web Application in Azure AD.

  • “ida:ClientId” represents the Application ID
  • “ida:Tenant” represents your domain name on Azure AD
  • "ida:AADInstance" represents login URL that allows accessing Azure AD for Authentication
  • "ida:PostLogoutRedirectUri" represents your local URL

 

The image below illustrates how the lines look after you paste them.

 Azure AD Authentication

Step 4

Right-click on your web application project and then add a file and name it “Startup.cs”. The file will contain a Startup class that has a void method “Configuration”.

The code below illustrates how the Startup class should be implemented

  1. using Owin;  
  2.   
  3. namespace WebApplication  
  4. {  
  5.     public partial class Startup  
  6.     {  
  7.         public void Configuration(IAppBuilder app)  
  8.         {  
  9.             ConfigureAuth(app);  
  10.         }  
  11.     }  
  12. }  

ConfigureAuth(app) method will be unrecognized because you don’t have a definition of it yet, its definition will be implemented in “Startup.Auth.cs” file.

Right-click on “App_Start” folder to add file and name it “Startup.Auth.cs”

When you create Startup.Auth.cs file visual studio will concatenate the name of the “App_Start” folder with the name of your project to form the namespace. Make sure to remove the “.App_start” from your namespace. It should look like “namespace WebApplication” as illustrated in the code below.

 Now, let’s see how you should code your “Startup.Auth.cs” file:

  1. using Microsoft.Owin.Security;  
  2. using Microsoft.Owin.Security.Cookies;  
  3. using Microsoft.Owin.Security.OpenIdConnect;  
  4. using Owin;  
  5. using System.Configuration;  
  6. using System.Globalization;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace WebApplication  
  10. {  
  11.     public partial class Startup  
  12.     {  
  13.   
  14. // Calling the keys values from Web.config file  
  15. private static string clientId =ConfigurationManager.AppSettings["ida:ClientId"];  
  16. private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];  
  17. private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];  
  18. private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];  
  19.   
  20. // Concatenate aadInstance, tenant to form authority value       
  21. private string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);  
  22.   
  23.   
  24.      // ConfigureAuth method  
  25.         public void ConfigureAuth(IAppBuilder app)  
  26.         {  
  27.               app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);  
  28.   
  29. app.UseCookieAuthentication(new CookieAuthenticationOptions());  
  30.   
  31. app.UseOpenIdConnectAuthentication(  
  32.   
  33.                 new OpenIdConnectAuthenticationOptions  
  34.                 {  
  35.                     ClientId = clientId,  
  36.                     Authority = authority,  
  37.                     PostLogoutRedirectUri = postLogoutRedirectUri,  
  38.                     Notifications = new OpenIdConnectAuthenticationNotifications  
  39.                     {  
  40.                         AuthenticationFailed = (context) =>  
  41.                         {  
  42.                             context.HandleResponse();  
  43.                             context.OwinContext.Response.Redirect("/Home/Index");  
  44.                             return Task.FromResult(0);  
  45.                         }  
  46.                     }  
  47.                 });  
  48.   
  49.   
  50.         } // end - ConfigureAuth method  
  51.   
  52.     } // end - Startup class  
  53. // end - namespace   

Step 5

Add AccountController to the Controllers folder. The controller AccountController will have two methods SignIn and SingOut.

  1. using System.Web;  
  2. using System.Web.Mvc;  
  3. using Microsoft.Owin.Security;  
  4. using Microsoft.Owin.Security.Cookies;  
  5. using Microsoft.Owin.Security.OpenIdConnect;  
  6.   
  7. namespace WebApplication.Controllers  
  8. {  
  9.     public class AccountController : Controller  
  10.     {  
  11.         // Sends an OpenIDConnect Sign-In Request.  
  12.         public void SignIn()  
  13.         {  
  14.             if (!Request.IsAuthenticated)  
  15.             {  
  16.   
  17.                 HttpContext.GetOwinContext()  
  18.                     .Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },  
  19.                         OpenIdConnectAuthenticationDefaults.AuthenticationType);  
  20.             }  
  21.         }  
  22.   
  23.           
  24.         // Signs the user out and clears the cache of access tokens.  
  25.         public void SignOut()  
  26.         {  
  27.      
  28.                 HttpContext.GetOwinContext().Authentication.SignOut(  
  29.                     OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);  
  30.               
  31.         }  
  32.           
  33.         
  34.     }  
  35. }  

Step 6

Add a partial view that will have links to the methods SingIn and SignOut of the AccountController

Create a partial view of the folder shared and name it “_LoginPartial.cshtml”

The code below illustrates how the code inside of the partial view should look.

  1. @if (Request.IsAuthenticated)  
  2. {  
  3.     <text>  
  4.         <ul class="nav navbar-nav navbar-right">  
  5.             <li>  
  6.                 @Html.ActionLink(User.Identity.Name, "About""Home"nullnew { id = "about" })  
  7.             </li>  
  8.             <li>  
  9.                 @Html.ActionLink("Sign out""SignOut""Account")  
  10.             </li>  
  11.         </ul>  
  12.     </text>  
  13. }  
  14. else  
  15. {  
  16.     <ul class="nav navbar-nav navbar-right">  
  17.         <li>@Html.ActionLink("Sign in""SignIn""Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>  
  18.     </ul>  
  19. }  

Open _Layout partial view and  call your partial view @Html.Partial("_LoginPartial") as illustrated below

 Azure AD Authentication

The configuration of your MVC Web application is done but remember you still need two values from Azure AD to complete the configuration.

Remember?! We will need values for "ida:ClientId" and for "ida:Tenant". Their values will be found in Azure AD portal.

In the the next step, we will see how to get them and save them in the web.config xml file

Section 2: Creation and Configuration of Azure AD to register the MVC Web Application

Go to https://azure.microsoft.com/en-us/free/  and then click on “Start Free” and create your account. The steps of creating an account are easy to do.

 Azure AD Authentication

After you created your account and you logged in to your Azure portal look up  “Azure Active Directory” in the left-side menu and click on it. If you don’t find it just type “Azure Active Directory” in the search bar on the top.

 Azure AD Authentication

After you click on “Azure Active Directory” you should see the screen in the image below then click on “Create a directory >” as shown in the image below.

 Azure AD Authentication

After you click on “Create a directory >” you will see a screen with fields to fill out. Fill it out and hit “Create”
you can choose any name you want but Initial domain name should be unique.

  • Organization name
  • Initial domain name (should be unique – I chose upsidedowntest)
  • Country or region
  •  Azure AD Authentication

After you click the “Create” button, it takes few seconds to setup your Azure AD environment, just wait and then you will see the screen below. Click on “here” link.

 Azure AD Authentication

After you click on the “here” link, then you will see the screen below.

 Azure AD Authentication

Copy #1, in our example, is “upsidedowntest.onmicrosoft.com”  you should copy it and save it in a notepad because it represents the value of “ida:Tenant” key in the Web.config xml file.

Then click on #2 “App registrations” to register the MVC Web Application you have created in our example is “WebApplication”.

After you click on “App registrations” then you will see the screen below. Click on “New application registration.”

 Azure AD Authentication

After you click on “New application registration” you will see the screen below with 3 fields to fill out.

Name, application type, and Sign-on URL.

Name field takes the name of our application “WebApplication”

Choose “Web app/API” for Application Type

Sign-on URL takes our application URL  https://localhost:44397/  (represents “ida:PostLogoutRedirectUri”). After you fill out all the fields hit “Create” button to register your web application

 Azure AD Authentication

After you click the “Create” button you will see the screen below that has information about your application. Copy the Application ID and save it in notepad because it represents the value of “ida:ClientId” key in the web.config xml file.

After you copy and save your Application ID and domain name (in our example is “upsidedowntest.onmicrosoft.com”) it  is time to go back to our MVC Web Application and paste the values copied from Azure AD environment in the web.config xml file.

 Azure AD Authentication

The screenshot below shows the values of “ida:ClientId” and “ida:Tenant”

 Azure AD Authentication

Congrats! You just set up the Azure AD Authentication with MVC Web Application.

Run your application and sign in, then the application will redirect you to Azure AD to do authentication.

 Azure AD Authentication

Enter your password and click “Sign in” button. 

 Azure AD Authentication

After you click on “Sign-in”  Azure AD will sign you in.

 Azure AD Authentication

You can also hide the item until the user is authenticated then reveal them, for example, you can use the code snippet below that lives in _layout partial view

 Azure AD Authentication

That’s it. You have learned how to set up an Azure AD Authentication with MVC Web Application

I hope you enjoyed the course and I'll see you later with another topic. 😊