Microsoft Azure Active Directory Identity And Access Management With MVC 5 Web Application

  • Sign-in to Azure Service Management portal with your Azure Subscription.

  • Click on Active Directory tab.
  • Once you are in the Active Directory tabàClick on New(+) , select Directory and click on Custom Create

    Azure

  • Provide your directory name along with domain name and region.
    Azure

  • Once you are inside your directory you can see various options like users, groups, applications, domains, directory integration etc.

    Azure

  • Click on user tab and click Add User.Give username and provide all necessary profile information.

    Azure

    Azure
  • Generate temporary password. Copy and save username and temporary generated password for future use.
  • So here you can see new user is created inside Azure Active Directory.

  • Now, open new Chrome instance in incognito mode and sign in to Azure portal with the newly created user.

  • Here, as the user account we have created is backed by Azure we will be able to login to the azure portal and will be allowed to reset password but that user doesn't have an Azure subscription so he/she can’t perform anything.

  • So go to azure.com and click on portals.

  • Give the details and reset the password.

    Azure

  • Reset temperorary generated password.
  • We would be able to reset password successfully but as we know our Azure AD users don't have an  Azure subscription.

  • Now, we will create our new Web Application and will provide authentication to that application.
  • We will write a code in such a way that we can Sign In to our Web Application using Azure AD.
  • Open VS 2013/2015 , select New ASP.NET Web Application .
  • Select MVC template and click on Change Authentication
  • Change your authentication to No Authentication and click OK.
  • Once application is created select your application name and go to properties, set SSL to true and copy the SSL Url. This would be our application Url.
  • Right Click on your Application NameàGo to Propertiesàselect Web category àReplace your project Url with the SSL Url.
  • Now open your web.config file and add below mentioned code
    1. <appSettings>  
    2.     <add key="ida:ClientId" value="6e19f05f-2b22-482b-abc1-f97fbc5bf0e4" />  
    3.     <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />  
    4.     <add key="ida:Tenant" value="krunalazureuser.onmicrosoft.com" />  
    5.     <add key="ida:PostLogoutRedirectUri" value="https://localhost:44334/" />  
    6.     <add key="webpages:Version" value="3.0.0.0" />  
    7.     <add key="webpages:Enabled" value="false" />  
    8.     <add key="ClientValidationEnabled" value="true" />  
    9.     <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
    10. </appSettings>  
  • Here, we defined four keys,

    • CliendID
      That we will get once we register our app with Azure AD

    • AADInstance [Azure AD Instance]
      That would be always https://login.microsoftonline.com/{0} , {0} is the country code . Only for China it is 1.

    • Tenant
      Our Azure AD domain name, which we have created for our user

    • PostLogoutRedirectUri
      SSL url to run our web application.

  • Now. Open package manager console and install following packages,

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

  • Microsoft.IdentityModel.Protocol.Extensions package provides an assembly containing classes which extend the .NET Framework 4.5 with base constructs from the OpenId Connect and WS-Federation protocols.
  • System.IdentityModel.Tokens.Jwt Includes types that provide support for creating, serializing and validating JWT tokens.
  • Microsoft.Owin.Security.OpenIdConnect is an Middleware that enables an application to use OpenIdConnect for authentication.
  • Microsoft.Owin.Security.Cookies is a Middleware that enables an application to use cookie based authentication, similar to ASP.NET's forms authentication
  • Microsoft.Owin.Host.SystemWeb enables OWIN-based applications to run on IIS using the ASP.NET request pipeline.

  • Once the packages are installed, Create a new class called StatUp.cs under App_Start folder.
  • Import below mentioned Namespaces,
    1. using Owin;  
    2. using Microsoft.Owin;  
    3. using Microsoft.Owin.Security.Cookies;  
    4. using Microsoft.Owin.Security.OpenIdConnect;  
    5. using System.Threading.Tasks;  
    6. using System.Globalization;  
    7. using System.Configuration;  
    8. using Microsoft.Owin.Security;  

  • Create variables inside StartUp.cs file. These variables will read data from web.config file. Create COnfigureAuthe method which takes an object of IAppBuilder Class and create Configuration(IAppbuilder app) method that will start your ConfigureAuth() method. and as per OWIN standards register your StartUp class with OwinStartUp assembly.
    1. [assembly: OwinStartup(typeof(WebAppConnectwithAzureAD.App_Start.StartUp))]  
    2. namespace WebAppConnectwithAzureAD.App_Start {  
    3.     public class StartUp {  
    4.         private static string clientid = ConfigurationManager.AppSettings["ida:ClientId"];  
    5.         private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];  
    6.         private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];  
    7.         private static string postlogoutredirecturi = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];  
    8.         string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);  
    9.         public void Configuration(IAppBuilder app) {  
    10.             ConfigureAuth(app);  
    11.         }  
    12.         public void ConfigureAuth(IAppBuilder app) {  
    13.             app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);  
    14.             app.UseCookieAuthentication(new CookieAuthenticationOptions());  
    15.             app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {  
    16.                 ClientId = clientid,  
    17.                     Authority = authority,  
    18.                     PostLogoutRedirectUri = postlogoutredirecturi,  
    19.                     Notifications = new OpenIdConnectAuthenticationNotifications {  
    20.                         AuthenticationFailed = context => {  
    21.                             context.HandleResponse();  
    22.                             context.Response.Redirect("/Error/messages=" + context.Exception.Message);  
    23.                             return Task.FromResult(0);  
    24.                         }  
    25.                     }  
    26.             });  
    27.         }  
    28.     }  
    29. }  
  • Now, Go to viewsàsharedàadd new viewàselect create as a Partial View.Name it like _LoginPartial.

  • Prepare _Login.cshtml page
    1. @if(Request.IsAuthenticated) { < ul class = "nav navbar-nav navbar-right" > < li class = "navbar-text" > Hello, @User.Identity.Name! < /li> < li > @Html.ActionLink("Sign Out""SignOut""Account") < /li> < /ul>  
    2. }  
    3. else { < ul class = "nav navbar-nav navbar-right" > < li > @Html.ActionLink("Sign In""SignIn""Account", routeValues: null, htmlAttributes: new {  
    4.         id = "loginLink"  
    5.     }) < /li> < /ul>  
    6. }  
  • Open _Layout.cshtml page and add reference of our partial view called _LogIn.cshtml

    Azure
  • Right click on controlleràAdd Empty MVC ControlleràAccountController

    Azure
  • Import namespaces in AccountController

    Azure

  • Remove, Index Action and Create this two methods in AccountController SignIn and SignOut respectively.
    1. public class AccountController: Controller {  
    2.     public void SignIn() {  
    3.         if (!Request.IsAuthenticated) {  
    4.             HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties {  
    5.                 RedirectUri = "/"  
    6.             }, OpenIdConnectAuthenticationDefaults.AuthenticationType);  
    7.         }  
    8.     }  
    9.     public void SignOut() {  
    10.         HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);  
    11.     }  
    12. }  

  • Now , we will register our web application with Azure and get the Client Id and place it in the web.config file
  • Go to your Active Directory and click on Applications

    Azure

  • Once you are inside Applications tab click on Add

    Azure

  • Select “Add an application my organization is developing”

    Azure

  • You can give any name, I prefer my webapp name from VS project.

    Azure

  • Provide Sign-On Url which is our SSL Url and APP ID URI which is https://domainname/appname

    Azure
  • Once the app is added go inside the app and click on Configure tab
  • From the configure section copy Client Id and place it into your web.config. Here, we copy the Client ID

    Azure
  • Paste it into the web.config file

    Azure

  • Build the application and run it in some another browser , not in the same browser where your Azure subscription is open or log out from the Azure subscription and run it.
  • You can see Application is running on the SSL Url and if your try to click on Home it will not allow you to navigate. Click on SignIn link.
    Azure

  • You can see you are redirected to Microsoft’s Azure AD SignIn page and it shows your web application name which you have registered with your Azure AD.
  • Provide your Azure AD based user credentials

    Azure
  • You can see we are inside our web application which is running on our on-prem environment with an Azure AD user.

    Azure


Similar Articles