Azure AD User Provisioning – Part 5

Hi everyone. I apologize for the delay in publishing the last post in this series. The past few months have been hectic. For this last post of the year I will be completing the series on provisioning in Azure AD.

As I’ve covered in earlier posts, there are a lot of options when provisioning to Azure AD including multiple GUIs and programmatic options. I’ve covered provisioning in the Azure Management Portal, Azure Portal, Office 365 Admin Center, and Azure Active Directory PowerShell v1 and v2. In this final post I will cover provisioning via the Graph API using a simple ASP .NET web application.

I was originally going to leverage the graph API directly via PowerShell using the .NET ADAL libraries and Invoke-WebRequest cmdlets. I’ve been playing around a lot with Visual Studio creating simple applications like the Azure B2B provisioning app. I decided to challenge myself by adding additional functionality to the ASP .NET web application I assembled in my previous post. I enjoyed the hell out of the process, learned a bunch more about .NET, C#, ASP .NET web apps, and applications built using the MVC architecture. Let’s get to it shall we?

Before we dive into the code and the methodologies I used to put together the application, let’s take a look at it in action. The application starts by requiring authentication to Azure AD.

1

After successful authentication, the main page for the website loads. You’ll notice from the interface that I used the sample ASP .NET MVC Web Application available in Visual Studio but added a new navigation link on the right hand side named Create User.

2

After clicking the Create User link, the user is redirected to a simple (i.e. ugly) web form where information about the new user is collected.

3

After the user hits submit, the new user is created in Azure AD and the information from the returned JWT is parsed and displayed in a table.

4

When we navigate to the Azure AD blade in the Azure Portal we see that Homer has been created and added to the system.

clearme

So you’re probably asking the question as to how complicated it was to put this application together? The answer may surprise you. It was incredibly simple. The most difficult part of the process was learning my away around C# and how MVC web apps are put together. For a skilled developer, this would have taken an hour versus the days it took me.

The first thing I did was do some reading into the Graph API, specifically around managing users. Microsoft has a number of great instructions located here and here. After getting familiar with the required inputs and the outputs, I built a new model in my application that would be used for the user form input.

6

Once I had my new model assembled, I then created two new views under a new folder named Create User. The view named Index is the view that takes the user input and the view named Results is the view that spits back some of the content from the JWT returned from Azure after the user is successfully created. Here is the code for the Index view.

7

And the code for the Results view.

8

After the new views were created, I then moved on to creating the guts of the new functionality with a new controller named CreateUserController. I was able to reuse some of the code from the UserProfileController to obtain the necessary OAuth access token to delegate the rights to the application to create the new user.

9

The remaining code in my controller came from a crash course in programming and MVC web apps. The first section of code calls the task to obtain the access token.

10

The next section of code creates a new instance of the user class and populates the properties with information collected from the form.

11.png

The final section of code attempts to create the new user and displays the results page with information about the user such as objectID and userPrincipalName. If the application is unable to create the user, the exception is caught, and an error page is displayed.

12

But wait… what is missing? I’ll give you a hint, it’s not code.

The answer is the appropriate delegated permissions. Even if the user is a global admin, the application can’t perform the actions of a global admin unless we allow it to. To make this happen, we’ll log into the Azure Portal, access the Azure AD blade, and grant the application the delegated permission to Access the directory as the signed-in user.

13

Simple right? The Azure Active Directory Graph Client libraries make the whole process incredibly easy doing a whole lot with very little code. Imagine integrating this functionality into an existing service catalog. Let’s say you have a business user who needs access to Dynamics CRM Online. The user could navigate to the service catalog and request access. After their manager approvers, the application powering the service catalog could provision the new user, assign the license for Dynamics CRM Online, and drop the user into the appropriate groups. All of this could happen without having to involve IT. This is the value of a simple API with a wonderful set of libraries.

Well folks that wraps up my last post the year. I’ll return next year with a series of deep dives exploring Microsoft’s newly announced Azure AD Pass-through authentication and SSO features. Have a happy holiday!

Azure AD ASP .NET Web Application

Hi all. Before I complete my series on Azure AD Provisioning with a look at how provisioning works with the Graph API, I want to take a detour and cover some Microsoft Visual Studio. Over the past month I’ve been spending some time building very basic applications.

As I’ve covered previously in my blog, integration is going to the primary responsibility of IT Professionals as more infrastructure shifts to the cloud. Our success at integration will largely depend on how well we understand the technologies, our ability to communicate what business problems these technologies can solve, and our understanding of how to help developers build applications to consume these technologies. In my own career, I’ve spent a significant time on all of the above except the last piece. That is where I’m focusing now.

Recently I built a small.NET forms application that integrated with the new Azure AD B2B API. Over the past few days I’ve been spending time diving with to ASP .NET Web Applications built with an MVC architecture. I decided to build an small MVC application that performed queries against the Graph API, and wow was it easy. There was little to no code that I had to provide myself and “it just worked”. You can follow these instructions if you’d like to play with it as well. If you’ve read this blog, you know I don’t do well with things that just work. I need to know how it works.

If you follow the instructions in the above link you will have a ASP .NET Web Application that is integrated with your Azure AD tenant, uses Azure AD for authentication via the Open ID Connect protocol, and is capable of reading directory data from the Graph API uses OAuth 2.0. So how is all this accomplished? What actually happened? What protocol is being used for authentication, how does the application query for directory data? Those are the questions I’ll focus on answering in this blog post.

Let’s first answer the question as to what Visual Studio did behind the scenes to integrate the application with Azure AD. In the explanation below I’ll be using the technology terms (OAuth 2.0 and Open ID Connect) in parentheses to translate the Microsoft lingo. During the initialization process Visual Studio communicated with Azure AD (Authorization Server) and registered (registration) the application (confidential client) with Azure AD as a Web App and gave it the delegated permissions (scopes) of “Sign in and read user profile” and “Read directory data”.

In addition to the registration of the application in Azure AD, a number of libraries and code have been added to the project that make the authentication and queries to the Graph API “out of the box”. All of the variables specific to the application such as Client ID, Azure AD Instance GUID, application secret key are stored in the web.config. The Startup.cs has the simple code that adds Open ID Connect authentication. Microsoft does a great job explaining the Open ID Connect code here. In addition to the code to request the Open ID Connect authentication, there is code to exchange the authorization code for an access token and refresh token for the Graph API as seen below with my comments.

AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
// MF -> Create a client credential object with the Client ID and Application key
ClientCredential credential = new ClientCredential(clientId, appKey);
// MF -> Extract the access token from cache and generate an authentication context from it
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
// MF -> Acquire a token by submitting the authorization code, providing the URI that is registered for the application, the application secret key, and the resource (in this scenario the Graph API)
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
return Task.FromResult(0);
}

Now that the user has authenticated and the application has a Graph API access token, I’ll hop over to the UserProfileController.cs. The code we’re concerned about in here is below with my comments.


{
Uri servicePointUri = new Uri(graphResourceID);
Uri serviceRoot = new Uri(servicePointUri, tenantID);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetTokenForApplication());
// MF -> Use the access token previous obtained to query the Graph API
var result = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync();
IUser user = result.CurrentPage.ToList().First();
return View(user);
}

Next I’ll hop over to the UserProfile view to look at the Index.cshtml. In this file a simple table is constructed that returns information about the user from the Graph API. I’ve removed some of the pesky HTML and replaced it with the actions.


@using Microsoft.Azure.ActiveDirectory.GraphClient
@model User
@{
ViewBag.Title = "User Profile";
}
"CREATE TABLE"
"TABLE ROW"
Display Name
@Model.DisplayName
"TABLE ROW"
First Name
@Model.GivenName
"TABLE ROW"
Last Name
@Model.Surname
"TABLE ROW"
Email Address
@Model.Mail

Simple right? I can expand that table to include any attribute exposed via the Graph API. As you can see in the above, I’ve added email address to the display. Now that we’ve reviewed the code, let’s cover the steps the application takes and what happens in each step:

  1. App accesses https://login.microsoftonline.com//.well-known/openid-configuration
    • Get OpenID configuration for Azure AD
  2. App accesses https://login.microsoftonine.com/common/discovery/keys
    • Retrieve public-keys used to verify signature of open id connect tokens
  3. User’s browser directed to https://login.microsoftonline.com//oauth2/authorize
    • Request an open id connect id token and authorization code for user’s profile information
  4. User’s browser directed to https://login.microsoftonline.com//login
    • User provides credentials to AAD and receives back
      1. id token
      2. access code for graph API with Directory.Read, User.Read scope
  5. User’s browser directed back to application
    • Return id token and access code to application
      1. id token authenticates user to application
      2. Access code for graph API with Directory.Read, User.Read scope temporarily stored
  6. Application accesses https://login.microsftonine.com//oauth2/token
    • Exchanges access code for bearer token
  7. Application sends OData query to Graph API and attaches bearer token.

That’s it folks! In my next post I will complete the Azure AD Provisioning series with a simple ASP .NET Web app that provisions new users into Azure AD.