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:
- Single point of failure. If the domain goes down everything goes down nobody has access to the resources like emails, SharePoint, etc.
- Not designed for internet scale.
- Too chatty. Any resource you access on your network requires you to keep talking to the domain controller.
Azure AD
- Azure AD Identifies Apps, APIs, and Users using internet ready standards
- It is designed for internet scale because it supports protocols like OAuth, WS-federation and more.
- It is a trust-based architecture, less chatty and there is no single point of failure.
- One of the biggest reasons that Azure AD is successful is that it is free.
- 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:
- Setup an MVC web application environment that can support Azure AD Authentication
- 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.
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”.
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
- <add key="ida:ClientId" value="" />
- <add key="ida:Tenant" value=" " />
- <add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
- <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.
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
- using Owin;
-
- namespace WebApplication
- {
- public partial class Startup
- {
- public void Configuration(IAppBuilder app)
- {
- ConfigureAuth(app);
- }
- }
- }
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:
- using Microsoft.Owin.Security;
- using Microsoft.Owin.Security.Cookies;
- using Microsoft.Owin.Security.OpenIdConnect;
- using Owin;
- using System.Configuration;
- using System.Globalization;
- using System.Threading.Tasks;
-
- namespace WebApplication
- {
- public partial class Startup
- {
-
-
- private static string clientId =ConfigurationManager.AppSettings["ida:ClientId"];
- private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
- private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
- private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
-
-
- private string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
-
-
-
- public void ConfigureAuth(IAppBuilder app)
- {
- app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
-
- app.UseCookieAuthentication(new CookieAuthenticationOptions());
-
- app.UseOpenIdConnectAuthentication(
-
- new OpenIdConnectAuthenticationOptions
- {
- ClientId = clientId,
- Authority = authority,
- PostLogoutRedirectUri = postLogoutRedirectUri,
- Notifications = new OpenIdConnectAuthenticationNotifications
- {
- AuthenticationFailed = (context) =>
- {
- context.HandleResponse();
- context.OwinContext.Response.Redirect("/Home/Index");
- return Task.FromResult(0);
- }
- }
- });
-
-
- }
-
- }
- }
Step 5
Add AccountController to the Controllers folder. The controller AccountController will have two methods SignIn and SingOut.
- using System.Web;
- using System.Web.Mvc;
- using Microsoft.Owin.Security;
- using Microsoft.Owin.Security.Cookies;
- using Microsoft.Owin.Security.OpenIdConnect;
-
- namespace WebApplication.Controllers
- {
- public class AccountController : Controller
- {
-
- public void SignIn()
- {
- if (!Request.IsAuthenticated)
- {
-
- HttpContext.GetOwinContext()
- .Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
- OpenIdConnectAuthenticationDefaults.AuthenticationType);
- }
- }
-
-
-
- public void SignOut()
- {
-
- HttpContext.GetOwinContext().Authentication.SignOut(
- OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
-
- }
-
-
- }
- }
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.
- @if (Request.IsAuthenticated)
- {
- <text>
- <ul class="nav navbar-nav navbar-right">
- <li>
- @Html.ActionLink(User.Identity.Name, "About", "Home", null, new { id = "about" })
- </li>
- <li>
- @Html.ActionLink("Sign out", "SignOut", "Account")
- </li>
- </ul>
- </text>
- }
- else
- {
- <ul class="nav navbar-nav navbar-right">
- <li>@Html.ActionLink("Sign in", "SignIn", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
- </ul>
- }
Open _Layout partial view and call your partial view @Html.Partial("_LoginPartial") as illustrated below
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.
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.
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.
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
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.
After you click on the “here” link, then you will see the screen below.
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.”
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
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.
The screenshot below shows the values of “ida:ClientId” and “ida:Tenant”
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.
Enter your password and click “Sign in” button.
After you click on “Sign-in” Azure AD will sign you in.
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
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. ๐