Azure Active Directory has emerged as a complete package for satisfying your application’s “Identity Management” needs. Be it the requirement of implementing Single SignOn( SSO) using on premises identity, Cloud only identity, Federation (or authentication) against Cloud SaaS applications (like Office 365, Salesforce, Dropbox, Facebook at work etc.), or the new age identity requirements like Multi factor authentication, Self-service management scenarios, Bring Your Own Device (BYOD) scenarios and device registrations; everything is possible today with Azure Active Directory. This step by step article will take you through the basics of Azure Active Directory and demonstrate the most common task of authenticating an ASP.NET MVC application using Azure Active Directory.
This article is published from the DNC Magazine for Developers and Architects. Download this magazine from here [Zip PDF] or Subscribe to this magazine for FREE and download all previous and current editions
Introduction to Azure Active Directory
In this article, we will explore the following important aspects of Azure Active Directory –
1. Terminologies and Concepts
2. Comparison with Windows Server Active Directory at conceptual level
3. Step by step guide to secure an ASP.NET MVC application using Azure AD with -
- a. Windows Identity Foundation
- b. OWIN KATANA (this is the future).
Let’s get started!
Applicable Technology Stack
Here are the pre-requisites for this article:
1. Valid Microsoft Azure subscription. Free trial is available here.
2. Visual Studio 2013 with update 5 Or Visual Studio 2015 or the Free Visual studio Community Edition.
Azure Active Directory: Terminologies and Concepts
Since its inception, Azure Active Directory has become the backbone to most of the services offered by the Microsoft Azure platform. Most of the times, whenever a developer hears about Active Directory, he/she gets nervous as a result of the huge number of features and terminologies involved with this concept. Ironically, once I tried to list down only the very important terminologies used in context of Active Directory in one PPT slide and this what I ended up with –
When you look at the above picture, how you do feel. Excited or Overwhelmed? The first thought that comes to our mind is why so much trouble? Let us filter through this plethora of huge bulky terminologies and focus on the ones we feel are the most important. Here it is –
This is our mental picture of Active directory and its terminologies. We always refer to the above 3 words when we talk about Active directory. So let’s first brush up on these basic, but important Active Directory terminologies.
Directory Service
In layman’s term, a directory is like a book containing alphabetical index of the names and addresses of people in a city or an area. Telephone directory was a popular form of directory. If we talk in technical terms, it is a mapping between names and values. If you see a Word Dictionary like Oxford, for each word, you will find many different meanings and definitions.
In case of software systems, the basic communication language is English (pun intended). Well it is not English, it is TCP/IP. So when any computer participates in TCP/IP communication, a numerical label is assigned to each computer and we call it IP address of the machine. Soon due to explosion of internet connectivity and desktop PCs; people found it difficult to remember the IP addresses of the computer to communicate with, therefore they decided to provide some user friendly names, something a user can easily remember. But again there were so many user friendly names required to be given, that mapping of those user friendly names to IP address number was a challenge to remember. Therefore a system was developed which remembers or maps the user friendly name to IP address so that users are freed from remembering this association.
This is called as Directory Service.
Domain Name System
So “Directory Service” is the same as telephone directory, but for computer systems, it has names and associated multiple IP address values in it. Every Directory Service contains many computers so to denote that these group of computers are part of this directory service and each computer within directory service, will have a unique numerical value which we call as IP address.
Directory service is a concept and many implementations were carried out from this concept. The most popular implementation is Domain Name System, commonly known as DNS. This implementation is very popular and is still used today for Internet and Private Network (organizations). Therefore directory service is commonly known and referred as DNS.
Windows Domain, AD and ADDC
What you see on the next diagram is the hierarchy of Directory Service and where DNS fits in. Similar to DNS, some other systems have been developed like NIS, NT domain and many more but they are not popular and are rarely used.
Directory service standards was well suited for internet services but there were some shortcomings, issues and security problems while implementing DNS for a private organization network. Therefore those standards were reformed and named as X.500.
I don’t know why but people always love giving absurd names to standards. X.500 represents a fantastic example of the same. No offence please, I am just expressing my disbelief! Or possibly I am dumb enough not able to understand the reasons behind this and many more naming conventionsJ.
These standards give you a way to develop a directory for private organization. So there are multiple implementations of X.500.
Now Microsoft created a special type of computer network based on TCP/IP in which, user accounts, computer info, printers, security principles can be stored on computers itself. This special computer network was called as Windows Domain. For this domain, Microsoft felt the need of Directory service to do the mapping. Therefore Microsoft also did the implementation of X.500 standards and came up with a product. This product was called as Active Directory.
So AD is a directory service for Windows Domain. The computers used for storing the information of Windows domain in Active directory are called as Domain Controllers or ADDC.
These AD based systems also had a requirement to connect to the internet, therefore DNS system was made a part of AD. So essentially AD and DNS are two different things and to support internet based connectivity for AD based resources, DNS was made a part of it.
So this is the general background of Active directory and how it came into existence. Does it make sense to you? Cool!
Now that we understood what active directory is, let’s understand what Azure Active Directory is by comparing them.
Comparing Windows Server AD and Azure AD
When you hear about Azure Active directory and provided you have background of Windows AD; the first thought that comes to mind is “Windows AD and Azure AD must be same with Azure AD being cloud offering”. Unfortunately, this is far from being true. Let’s see why.
Windows Active Directory offers 5 core services and they are –
ADCS – Active Directory Certification Services – Offers public key certificates if you wish to implement certificate based authentication.
ADRMS – Active Directory Rights Management System – It allows to create policies that enforce control over access to information. The idea of RMs is unique and protection provided to any piece of information is Persistent. This means protection rules travels with data and can’t be separated.
ADDS – Active Directory Domain Services – Allows to manage network resources such as computers and users within network and integrates with DNS service of Active Directory.
ADFS – Active Directory Federation Services – Used for federating the identity of user and based on WSFederation standards.
ADLDS – Active Directory Light Directory Services – Similar to ADDS. Just based on LDAP standards.
All of these services are installed or configured on one server to which we usually refer to as Active Directory Domain Controller (ADDC).
On the other hand, Azure AD offers you 2 key solutions only –
1. Identity management solution.
2. Azure AD Domain Services (AADDS - in preview as of today).
Windows Server AD is not an identity solution but Azure AD is. Window server Active directory is designed to operate in corporate networks where enterprise has full control over topology. This topology exposes services to manage –
- Identity
- Servers
- Workstations
- Security
- Network policies and so on.
And these are exposed through enterprise protocols like LDAP, Kerberos, DNS, AD replication and so on.
On the other hand, Azure AD is focused only on one area – Identity throughout the internet. Here –
- Types of communication is http and https.
- Types of devices are different and not only corporate assets
- Protocols are SAML, WS Federation, OAuth, OpenId
- And instead of LDAP, you talk here about REST API.
This ability of Azure AD enables us to make application hosted as Software as a Service (SaaS) or even connect to existing many enterprise grade SaaS applications like SalesForce, Office 365, Box, Facebook at work and so on.
How to create Azure Active Directory?
As of today, most of the services can be used from the new Azure portal (http://portal.azure.com ). However there still are some services for which we have to fall back to the full management portal (http://manage.windowsazure.com/). As of this writing, Azure AD can be managed using the old portal only.
If we click on the Active directory option, by default you will see at least one directory already present. This is the default active directory under which your Azure subscription is present and one directory can have multiple subscriptions within it. To keep things simple, let’s first create a new directory itself.
Click on New > App Services > Active Directory > Directory > Custom Create as shown below –
Provide the name of the directory as “DotNetCurryAD” and rest of the values as shown in the image below. Of course you may choose the country of your choice. Then click on Complete to create an Azure AD.
Open the created Azure AD and click on “Users” tab. The current logged in user automatically becomes “global administrator” in the newly created directory, giving the user full access to the entire Azure active directory. Various admin roles in Azure AD and their descriptions are well documented at http://bit.ly/1pb1V5C . With this, let’s go back to understand some more concepts.
Structure of Azure Active Directory
If you have observed the Fully Qualified Domain Name (FQDN) of the AD we created, it is dotnetcurryad.onmicrosoft.com. From this name, onmicrosoft.com is the shared domain. This means Microsoft.com already exists and we are using a part of it. So as you can see in the following diagram, Azure active directory is a directory service that lives on the cloud. It is highly scalable, distributed service that runs across many servers in data centers of Microsoft, across the world. And most importantly, it is offered as a Platform as a Service (PaaS) offering. What does that mean? You don’t have direct access to underlying servers, but the hardware and software is delivered to you as a service. But then the next question that comes to mind is how do we access it? As “endpoint and interfaces”. So the service exposes interfaces such as directory graph API; and authentication endpoints such as OAuth, SAML, WSFederation and a couple of more in the near future.
Important: This active directory service contains the data which is owned by each customer who is a tenant of the directory. Pay attention to “Tenant of the directory”. Let’s understand more about it in the next section.
Why Azure AD is called as Multi-Tenant Service?
The dictionary meaning of a tenant is a person who hires a property on rent. Similarly you may own an office space in a building. This building may be shared by multiple offices. So your office can be considered as a tenant of the building. This building provides all the services to carry out your business well, including security. It also ensures you are isolated from other organizations hosted in the same building.
In Azure, Active Directory service is exactly similar to this concept. It contains many such tenants. So if we want to give it a fancy name, we can say Azure active directory is Multi-Tenant service.
So coming back to the statement we made earlier, “this active directory service contains the data which is owned by each customer who is a tenant of the directory”.
There are lots of tenants inside the service. These tenants have names like KunalAD.onmicrosoft.com. But they can also be configured for kunalad.com. Each customer looks after their data in each tenant, whereas Microsoft looks at the entire Azure Active directory service to keep it up and running all the time. And then you manage, change, update the data using portal. So when you hear the term saying Azure AD is multi-tenant service, this is what it exactly means.
Alright, I have tried my level best to explain Azure AD concepts using the simplest language and diagrams; and now is the time for some action. Let’s build an application which can authenticate against Azure AD.
Secure ASP.NET MVC application using Azure Active Directory
There are 2 popular implementation approaches used for securing ASP.NET MVC application using Azure active directory –
1. Using OWIN KATANA
2. Using Windows Identity Foundation (WIF)
We will build the application using both the techniques and with the “Ws-Federation” protocol which is quite common. Let’s start with OWIN first.
Securing ASP.NET MVC application using Azure Active Directory and OWIN KATANA
We will build our entire application from scratch. Create a simple ASP.NET MVC application using Visual Studio. Name the application as “DNCMvcApp”. Select the template as MVC, authentication as “No Authentication” and uncheck the checkmark of “Host in the cloud” for now. Click Ok to proceed ahead and create the application.
Configuring Https
We need to configure the project to run on https. Therefore open the properties by selecting the project from Solution Explorer and by pressing “F4”, and mark the property “SSL Enabled” as true and copy the new URL configured under property “SSL URL”.
Now open the project properties by right clicking on the project from Solution Explorer. Paste the copied URL to web properties as shown here –
Build and run the application. You may be prompted by a certificate error which you can safely ignore and proceed ahead. This error is because of the self-signed certificate. Make sure that application runs on the same URL which in my case is https://localhost:44307/ as shown here.
Add important nuget packages
Open “Package manager console” and run the following commands to add required references to the application.
Rebuild the application to check if it builds successfully.
Register application in Azure Active Directory Tenant
To secure our DNCMvcApp using Azure AD, our application should trust Azure AD. Similarly Azure AD will need to know about our application to trust it. This can be achieved by simply adding the application in our Azure Active Directory Tenant “dotnetcurryad.onmicrosoft.com”.
Open Azure AD from the Azure portal and click on the Applications tab. Select the option “Add an application my organization is developing”.
Name the application as “DncMvcApp” and select the type as “Web application and/or WEB API”.
The type would of course be web. If I want my desktop application authenticated against Azure AD, then we need to select the Native Client Application option. On the next screen, we need to provide SignOn URL and App Id URI. The application URL is https://localhost:44307/ and this is nothing but our signon url. This is important, your application url must match the sign on url. Therefore we will put the same https url of our application copied from project properties, in here.
The App Id URI is the identifier for the application, or if I have to put this in fancy words, in WS-Federation parlance, it is the realm of the application. You can choose any identifier that makes sense to you, as long as it is unique within the active directory tenant. I usually try to follow a memorable schema. Remember, given that this is a URI, this value does not need to correspond to any real network address! And of course here I assume you understand difference between URI and URL. If not refer to identity guru Vittorio’s article (http://bit.ly/1TId5vc) for differences between URL, URI and URN.
We put the value as http://dotnetcurryad/wsfedsample_owin. This is an Owin WsFed sample and under DotNetCurryAD tenant. Click OK to proceed.
This completes the configuration on Azure AD side. Let’s go back to Visual Studio.
Add and configure Startup class
Startup.Auth.cs is a very important class and is used for OWIN initialization. In Visual Studio, right click on App_Start > Add > New Item > Class. Name the class file as Startup.Auth.cs. Copy paste the following code segment in the same class –
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.WsFederation;
using Owin;
using Microsoft.Owin.Security;
...
namespace DNCMvcApp
{
public partial class Startup
{
//
// Client ID is used by the application to uniquely identify itself to Azure AD.
// Metadata Address is used by the application to
// retrieve the signing keys used by Azure AD.
// The AAD Instance is the instance of Azure, for example public Azure or Azure China.
// The Authority is the sign-in URL of the tenant.
// The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out.
//
private static string realm = ConfigurationManager.AppSettings["ida:Wtrealm"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string metadata = string.Format("{0}/{1}/federationmetadata/2007-06/federationmetadata.xml", aadInstance, tenant);
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = metadata,
Notifications = new WsFederationAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("Home/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
}
}
Remember Owin is a specification and KATANA is Microsoft’s implementation of this specification. The code we just saw is a standard code a startup class can have. OWIN basics and startup class is already covered in a previous article of authenticating ASP.NET MVC using Owin Katana and ADFS [link - https://www.dotnetcurry.com/windows-azure/1166/aspnet-mvc-multiple-adfs-owin-katana] so let’s not spend more time on this. The code is quite self-explanatory with the comments.
Now we will add an OWIN startup class and invoke the ConfigureAuth() method of startup.auth.cs class. Right click on project > Add > Add OWIN Class. Provide the name as Startup.cs. Note, earlier the class file was Startup.Auth.cs, whereas this class is named as Startup.cs.
Replace the code with the following –
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
So essentially we are just invoking ConfigureAuth() method in this class. Here we complete the startup class configuration.
Configure Login page
In Views > Shared folder, right click on Add New Empty View. Name it as _LoginPartial.cshtml. Replace the code in this file with the one given here –
@if (Request.IsAuthenticated)
{
<text>
<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>
</text>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Sign in", "SignIn", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
Here in this file, we are simply creating a SignIn and SignOut button and telling the application to invoke Account controller action on SignIn button click. We are also adding the name of the user at runtime through the code User.Identity.Name, to welcome him/her!
Now we need to link this _loginPartial.cshtml on layout page as highlighted below, therefore change the code of Layout.cshtml to the following code –
If we refer to the _LoginPartial.cshtml code, you will see that we are referring to the controller name as Account for sign in and out functionality. Therefore let’s add AccountController in controller’s folder. Right click on Controllers folder > Add > Controller > MVC 5 Controller – Empty > name as AccountController. Replace the following code –
// The following using statements were added for this sample.
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.WsFederation;
using Microsoft.Owin.Security;
namespace DNCMvcApp.Controllers
{
public class AccountController : Controller
{
public void SignIn()
{
// Send a WSFederation sign-in request.
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, WsFederationAuthenticationDefaults.AuthenticationType);
}
}
public void SignOut()
{
// Send a WSFederation sign-out request.
HttpContext.GetOwinContext().Authentication.SignOut(
WsFederationAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
}
}
}
If you observe the code, we are invoking the Challenge() method, and we are checking the return code. If it is 401, it means unauthorized, so we are asking the user to login again.
Web Config changes
Registration application is already done in Azure Ad. Now we need to make changes in our application to make our application know about Azure AD. So add the following configuration settings in web.config file –
<add key="ida:Wtrealm" value="[Enter the App ID URI]" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com" />
<add key="ida:Tenant" value="[Enter Azure AD tenant name]" />
If we replace the values in the above configuration settings with our values, then it would be as follows –
<add key="ida:Wtrealm" value="http://dotnetcurryad/wsfedsample_owin" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com" />
<add key="ida:Tenant" value="dotnetcurryad.onmicrosoft.com" />
We are done with required application changes and all set to run it. Press F5 to run the application in debug mode. Click on Sign In button. Now let’s go back to understand more about users in Azure active directory.
Add School or Work account User to Azure AD tenant
Microsoft always reiterates that they are making life of developers simple, but as per my experience, sometimes things are not so simple with Microsoft (pun intended). It starts with your account itself. First we need to understand the different types of accounts Azure AD supports. As of today you have 2 accounts –
- Microsoft Account (previously Live ID)
- Work or school account (previously Organizational account)
It sometimes becomes hard to keep up with frequent name changes. For example when Azure was introduced it was “Windows Azure” now everyone talks about “Microsoft Azure”. Similarly Live Id is now called as Microsoft account and Organizational account is now called “Work or School account”.
So if you create a new user in Azure AD, then it becomes “Work or School account” or “Azure AD based account”.
When we created an Azure AD tenant, the current logged in user of the Azure Portal automatically became the global admin of the tenant. The current logged in user in Azure portal I have used is “Microsoft Account and not the Azure AD account”.
For signing in to the DNCMvcApp we can definitely use a Microsoft account user, but this is NOT CORRECT.
Microsoft Account can be used with Azure Active Directory when they are used with Microsoft Applications, like the Azure Portal. Microsoft Accounts are not expected to work with applications registered by developers YET. Unfortunately if you use it today, it may work because it is a bug, which hopefully will be rectified soon.
So ideally only Azure AD based user should be allowed to login in DNCMvcApp application. So let’s create a user in Azure AD tenant.
Click on Add User button in Azure AD tenant page in Azure Management Portal. Provide the values as shown here –
In the last screen, a prompt will appear to “Create a temporary password”. Click on Create button and record this password for future use. When you login to DNCMvcApp using this user, you will need to change this temporary password to a new one.
So this user DNCAdmin@dotnetcurryad.onmicrosoft.com now we will be used for logging in to the DNCMvcApp application.
Run the application and click on SignIn button. Once prompted, put the DNCAdmin credentials. You will prompted immediately to change the temporary password as shown here –
Once you update the password, you will be logged in to DNCMvcApp application and username will appear in right most corner as shown here –
Secure ASP.NET MVC application using Azure AD and WIF
In order to secure our MVC application using Azure AD and Windows Identity Foundation (WIF), please refer to an article written by Mahesh Sabnis - https://www.dotnetcurry.com/windows-azure/1123/secure-aspnet-mvc-azure-using-active-directory-signon.
That’s all. As we just saw, it is relatively quite easy to secure an ASP.NET MVC application using Azure Active Directory tenant either using WIF or OWIN with Ws-Federation.
Conclusion
In this article, we saw some important and essential concepts around Azure Active Directory. We also explored the structure of Azure AD, and why it is commonly referred to as multi-tenant service. We also saw how an ASP.NET MVC application can be secured with Azure Active Directory using OWIN and WIF with WS-Federation protocol.
Download the entire source code from GitHub at
bit.ly/dncm23-azure-active-dir
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Kunal Chandratre is a Microsoft Azure MVP. He is working as Azure SME in leading software company in (Pune) India. He also works as a Freelancer with various organizations for Azure support and provides quick start trainings on Azure to corporates and individuals on weekends. He regularly blogs about his Azure experience and is a very active member in various Microsoft Communities and also participates as a ‘Speaker’ in many events. You can follow him on Twitter at: @kunalchandratre or subscribe to his
blog