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";
Display Name
First Name
Last Name
Email Address

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
    • Get OpenID configuration for Azure AD
  2. App accesses
    • Retrieve public-keys used to verify signature of open id connect tokens
  3. User’s browser directed to
    • Request an open id connect id token and authorization code for user’s profile information
  4. User’s browser directed to
    • 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
    • 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.

Azure AD User Provisioning – Part 4

Today I will continue my series in Azure AD User Provisioning. In previous posts I looked at the GUI methods of provisioning users. I’ll now begin digging into the methods that provide opportunities for programmatic management of a user’s identity management lifecycle. For this post we’ll cover every IT Professional’s favorite Microsoft topic, PowerShell.

Microsoft has specific PowerShell modules for administration of Azure Active Directory. Microsoft is in the process of transitioning from the MSOnline (Azure Active Directory PowerShell v1) to the AzureAD module (Azure Active Directory PowerShell v2). At this time the AzureAD PowerShell module is in public preview with plans to migrate all the functionality from the MSOnline module to the AzureAD module. Until that point there will be some activities you’ll need to do in the MSOnline cmdlets.
Creating a new user using the MSOnline module (lovely referred to as the “msol” cmdlets) is a quick and easy simple line of code:

New-MsolUser -userPrincipalName -DisplayName "Some User"

The user can then be modified by using cmlets such as Set-MSolUser, Set-MsolUserLicense, Set-MsolUserPrincipalName, Set-MsolUserPassword, Remove-MsolUser. Using this set of cmdlets you can assign and un-assign user licenses and manage the identity lifecycle of the user account.

There are some subtle differences in the MSOnline and AzureAD cmdlets. These differences arise due to Microsoft’s drive to make the experience using PowerShell in the Azure AD module similar to the experience of using the Graph API. The AzureAD cmdlets are much more full featured in comparison to the MSOnline cmdlets. Close to every aspect of Azure AD can be managed across the board beyond just users. Here is an example of how you would create a user with the new cmdlets:

New-AzureADUser -UserPrincipalName -AccountEnabled $False -DisplayName "user" -PasswordProfile $UserPasswordProfile

You’ll notice a few differences when we compare the minimum options required when creating a user with the MSOnline cmdlets. As you’ll notice above, there are not just more required options, but one that make look unfamiliar called PasswordProfile. The Password profile option configures the user’s password and whether or not the user is going to be forced to change the password at next login. I struggled a bit with getting the cmdlet to accept the PasswordProfile, but the documentation on the Azure Graph API and a Microsoft blog that provided some information. It can be set with the following lines of code:

$UserPasswordProfile = "" | Select-Object password,forceChangePasswordNextLogin
$UserPasswordProfile.forceChangePasswordNextLogin $true
$UserPasswordProfile.password = "some password"

So what is the big difference between the MSOnline and AzureAD cmdlets? Well it comes down to the API each uses to interact with Azure AD. The MSOnline (aka Azure AD PowerShell v1) uses the old SOAP API. Oddly enough it uses the same SOAP API that Azure AD Connect uses. If you’ve read my Azure AD Connect – Behind the Scenes series, you’ll know notice the similarities in the Fiddler capture below.


The AzureAD cmdlets (aka Azure AD PowerShell v2) uses the Graph API. In the Fiddler capture below you can see the authentication to Azure AD, obtaining of the authorization code, exchange for bearer token, and delivery of the bearer token to the graph API for the user information on Dr. Frakenstein. Check out the screenshot from Fiddler below:


As you can see, PowerShell presents a powerful method of managing Azure AD and its resources. Given how familiar IT professionals are with PowerShell, it presents a ton of opportunities for automation and standardization without a significant learning curve. Microsoft’s move to having PowerShell leverage the power of the Graph API will help IT professionals leverage the power of the Graph API without having to break out Visual Studio.

In my next post I’ll write a simple application in Visual Studio to demonstrate the simplicity of integration with the Graph API and the opportunities that could be presented to integrating with existing toolsets.

Azure AD User Provisioning – Part 3

In this entry I’m going to look at how provisioning users differs in the Azure Management Portal and the Azure Portal. The Azure Management portal was used heavily for all Azure administration prior to the introduction of the Azure Resource Manager deployment model a year or so ago. To my knowledge there isn’t much functionality that hasn’t been migrated to the Azure Portal exempting management of Azure Active Directory. This remaining piece is in the process of being moved to the Azure Portal and is currently in public preview with some limitations. This means that if you’re administering Azure AD you’re going to need to use the Management Portal for a while longer.

Unlike the Office 365 portal, the Management portal feels very dated. The initial dashboard that appears after authentication will list any classic deployment model resources and directories the authenticated user has control over.


First I will select one of the directories and dig into the interface. Immediately you’ll notice a number of configuration options available. Since I’m focused on user provisioning, I’ll very briefly describe the purpose of the other sections.

  • Groups – Used to manage the group lifecycle of Azure AD groups
  • Applications – Used to add new applications from the application gallery and register custom and third party applications
  • Domains – Used to manage additional DNS domains that have been associated with the tenant
  • Directory Integration – Used to configure support for synchronization using a tool such as Azure AD Connect
  • Configure – Used to manage the configuration of Azure AD including password reset policies, MFA, device authentication options, group management, who can invite guests, and the like
  • Reports – Used to run the many reports available with standard Azure AD and Azure AD Premium
  • Licenses – Used to assign Azure AD Premium licenses; not sure if any licenses beyond that, but does not seem capable of handling O365 licenses.

Now let’s get back to user provisioning. Next up I’ll head to the Users section. Here there is a listing of all members and guests within the directory.


To create a new user I’ll click the Add User icon at the bottom of the page which will bring up the window below where I can configure the user name.


In the next window I will add a first name, last name, display name, and pick a role. Notice anything different? Here the only options to configure the Azure AD roles as described here. There are no Office 365 roles to choose from here. Additionally the user can be enabled for Azure MFA (the checkbox is hidden under the listing of roles).


In the last window I’m prompted to create an auto-generated temporary password for the user. Notice the option to create a password and enforce password change at first sign in aren’t there like O365? After the create button is hit a password will be automatically generated and will need to be delivered to the user out of band. Quite basic when compared to the Office 365 Admin Center isn’t it?


After the user is created the user can be modified in the Profile and Work Info sections. Profile is for your basic information and configuration while Work Info is similar to the contact information section in the Office 365 Admin Center with some additional options to configure the users authentication phone number and email address. The Devices and Activity sections providing reporting on the user’s activities.


Let’s now ditch the old and embrace the new by examining provisioning in the Azure Portal. Prior to a few months back, the only some of the Azure AD functionality could be administered in the Azure Portal including Azure AD Privileged Identity Management, Azure AD Identity Protection, Azure AD Connect Health, Azure AD Cloud App Discovery and Azure AD B2C (which is even mixed with the Management Portal). Microsoft has recently begun to migrate the administration of Azure AD to the Azure Portal to centralize administration of Azure resources.

The Azure portal is accessible through by navigating to this link. After authentication the dashboard will load up displaying any resources that have been pinned. Click on the Azure Active Directory blade as highlighted in red in the screenshot below.


You’ll notice right off the bat that the interface is very slick, is intended for power users, and provides some useful summary analytics. I hadn’t poked around the new blade in a while and it looks like they’ve improved the functionality quite a bit. There doesn’t seem to be much missing beyond the ability to create new directories, assigning licenses, and reviewing the holistic audit logs. One item I did observe which is worth calling out is the app registration interface has been refined and made more slick. This is a big improvement from the similar interface in the Management Portal.


By navigating to the All Users blade and clicking the add button a new user can be created. This will bring up a new blade that allows for basic configuration of key pieces of information like user, first name, last name, job title, description, group membership, and Azure AD roles. The experience is quite similar to the Management Portal experience. Notice that the password again is pre-generated and does not allow setting a customer password or the option to turn off the enforcement of a password change at first login.


After the user is created it can be modified by clicking on the user which opens a new blade. This new blade allows for contact information about the user to be edited, assignment of Azure AD Roles, and assignment Azure AD group memberships. One neat feature is the Azure Resources option. This opens up a new blade that enumerates the user’s effective access to various Azure resources. Providing reporting on an effective user’s access is one thing Microsoft has never done effectively on-premises so a feature like this is nice to see, especially with the additional complexity the scale of cloud introduces. Finally, you’re provided some options to review the audit logs and sign in reports for the user (another neat feature). Like the Azure Management Portal, there is no quick and easy GUI-based functionality to restore deleted users in the Azure Portal at this time.


Well folks that is the overview of three out of four of the GUI provisioning methods. The fourth option is to provision natively through an on-premises Active Directory and synchronize those users to the cloud with a synchronization tool such as Azure AD Connect. There is plenty of documentation on what that process looks like already available. If you’re hungry for more, you can check out my previous series Azure Active Directory Connect – Behind the Scenes.

Let’s take a moment to summarize what we’ve learned:

Office 365 Admin Console

  • Simple and ideal for business users and Tier 1 support
  • Limited in its ability to administer Azure AD
  • Only GUI option for assigning Office 365 licenses
  • Only GUI option for assigning Office 365 roles
  • No B2B or B2C support
  • Bulk user creation capabilities
  • Best option for restoration of a deleted user

Azure Management Portal

  • Legacy portal being replace by Azure Portal
  • Only GUI option for creating additional standard and B2C directories
  • Only GUI option for adding B2B users
  • No support for bulk user creation or restoration of deleted users
  • Support of legacy Azure AD configuration items; no support for configuration of B2C policies, Identity Protection, Privileged Identity Management

Azure Portal

  • Future one-stop shop for Azure AD administration
  • Seems to supports all functionality of Azure Management Portal except creation of new directories
  • GUI options for B2C policies, management of Identity Protection, Privileged Identity Management, Azure AD Connect Health, and Azure AD Proxy
  • No GUI option for adding B2B users
  • No support for bulk user creation or restoration of deleted users
  • Analytics built into administrative tools
  • Robust application registration features

So what does this all mean? Well it means that if you need to administer identity functionality via the GUI, you’re going to need to use a combination of the Office 365 Admin Console, the Azure Management Portal, and the Azure Portal. I expect within the next 3-6 months the remaining functionality in Azure Management Portal will be completely migrated to the Azure Portal. Businesses should focus their Tier 1 and business staff on learning the Office 365 Admin Console while Tier 2 and Tier 3 staff should focus on learning the Azure Portal.

Now that I’ve dug into the GUI options, I’ll next explore how the APIs and PowerShell provide opportunities for automation and integration with 3rd party and custom identity management solutions that may already exist on premises. See you then!

Azure AD User Provisioning – Part 2

Hello again. Today I will continue this series by examining the GUI options available within Microsoft’s Azure offerings to provision new user accounts. I am going to focus on member user objects and not guests for this series.

There are four native GUI options available that can be used to provision new user accounts in Azure Active Directory.

  1. Office 365 Administration Center
  2. Azure Management Portal
  3. Azure Portal
  4. ADUC/ADAC then synchronization to Azure AD

I’ll start with the Office 365 Admin Center. The Office 365 Administration Center is where most business will find themselves provisioning user accounts due to the popularity of the products under the Office 365 umbrella. The Admin Center provides an interface that is sleek and simple to navigate. The simplicity comes with a price. Administration of many aspects of Azure AD must be done outside of the Admin Center. This registering custom applications and applications from the application gallery, creation of additional directories such as B2C directories, B2B imports, and much more. Microsoft seemingly intends this interface to be business friendly administration endpoint for the Office 365 suite and rightfully assumes the consumers of this endpoint need simplicity.

I’ll now create a new user account. We first need navigate and login to the Office 365 portal. After the user authenticates the Office 365 home page that lists out the various applications the user has access to. I’ll next click on the Admin icon to enter the Admin Center. Next I will navigate to the Users section and select the Active Users section. This will bring us up a listing of the users currently in the Azure AD tenant associated with the Office 365 subscription.


When I hit the Add User button a new blade opens where the key components of the user’s account can be configured. This includes the first name, last name, user name and the like as seen in the screenshot below.


Let’s take some time to dig through the remaining sections.

First up is the contact information section. On-premise Active Directory administrators will recognize these fields from the various tabs in ADUC.


Next up is the password section. Here I have the option of creating a password or auto-generating a password and turning on or off the enforcement of a password change at first sign-in. I don’t recall there being an option to create a password a few months back when I was playing with the Admin Center, but that is one of the many lovely aspects of SaaS, continuous change and improvement.


Next up is the Roles section. Here there is an option to assign the user to the standard Azure AD roles or Office 365 roles. You can read more about these roles here.


Finally, the Licenses section allows for assignment of Azure AD and Office 365 licenses to the user account.


After the user is created it can be modified by clicking on the user object. Contact information about the user, membership into Azure AD groups, MFA enforcement, and product specific settings for the user can be modified in this blade.


The restoration of deleted users is simple and quick via the Deleted Users section. If only Microsoft had made it this easy in the old days of on-premises Active Directory prior to the Active Directory Administration Center.


Users can also be added in bulk by uploading a CSV file by hitting the More button in the Active Users section.


The Office 365 Admin Center interface is sleek and simple, perfect for a business user or Tier 1 support staff. So what’s the problem? No matter how simple the interface, it’s another process and interface staff need to learn. There is also no way to technically enforce standards for data input. What if what user puts MA and another puts Massachusetts? What about a user who misspells accountant in the job title field? Human error and lack of standardization can make for some nasty operational headaches, not to mention security risks. If an organization wants to limit the new processes and interfaces its staff needs to learn (because really, where is the business value in that?) as well as making sure the data about a user is standardized and correct, making these changes programmatically is the way to go.

In my next post I’ll cover both the Azure Management Portal and the Azure Portal.

Azure AD User Provisioning – Part 1

Welcome back! Over the past year I’ve done a number of deep dives into Azure AD authentication, but what is authentication without an identity? They have to get there somehow, right? Gone are the days of legacy protocols such as LDAP or executing a command to a database to provision a local user. Identity as a service offerings such as Azure AD introduce whole new ways to provision users, both manually through the GUI and through programmatic methods such as PowerShell or the Graph API. For this upcoming series of blogs I’m going to cover the many options available with Azure AD and the plusses and minuses of each.

Let’s begin this series by talking about “legacy” tools versus “modern” tools. What do I mean by legacy? Well I mean administrative graphical user interface (GUI) options. Why are administrative GUIs legacy? Well, cloud is primarily about automation, scale, and simplicity. To achieve those ideals, “cloud” services (whether they are IaaS, PaaS, SaaS, or IDaaS) must be capable of integrating well with other solutions, whether they be COTS or custom. Pay attention to the word “integration” people. It is more important than ever.

Administrative GUIs represent the old IT where the business had to depend on IT to administer and support its technologies. This was costly in the ways of labor, time, and complexity. The focus on standardized application programming interfaces (APIs) that is happening in the cloud is attempting to streamline this process for the business. These APIs provide a programmatic method of integration with the cloud solutions to take the middle man (IT) out of the equation and put the business users in the driver’s seat. Existing COTs or custom applications can be integrated directly with these APIs to simplify and automate a number of processes that typically fell into IT’s realm.

So what are some examples?

  • Scenario: Business user needs to share a document with a partner company

    In the “old” days, the business would have to rely on IT to setup complicated VPN solutions to allow for connectivity and either provision users directly in the identity data store or configure Active Directory trusts. With the standardized APIs emerging in the cloud, an existing identity management system can be directly integrated with an IDaaS API.

    If the business takes advantage of the programmatic access, the business user clicks a button of the person or persons he or she wishes to share the document with, the request goes to an approver such as the data owner, and the provisioning is done automatically by the application. No service requests or multiple day turnarounds from IT required here. The value presented by IT in here was the initial integration, not much else.

  • Scenario: Business focuses on application development and a developer requires a new web instance to test code

    In “legacy” IT the developer would need to submit a request to IT to provision a server, install and configure the appropriate middleware, and have security staff verify the server and applications have been configured for compliance. The developer would then need to wait to be provisioned for access as well as deal with the continued maintenance of the web instance. All of this took time and this was time the developer wasn’t developing, which impacts the businesses ability to deliver the product and service they’re in business to deliver.

    We know the value that PaaS provides here, but what about the APIs? Well, envision a service catalog where a developer requests an instance of a web platform that is automatically provisioned and configured to the businesses baseline. Where was IT in this scenario? They setup the initial integration and keep the baselines up to date, and that’s it. Not only does the business save money by needing less IT support staff but its key assets (developers) are able to do what they’ve been hired to do, develop, not submit requests and wait.

In the above two scenarios (and there are oh so many more), we see that IT professionals can no longer focus on a single puzzle piece (server, OS, networking, identity, virtualization, etc), but rather how all of those puzzle pieces fit or “integrate” together to form the solution. Cloud as-a-service offerings made the coffin and simple APIs are the nails sealing the coffin finally putting the “legacy” IT professional to rest.

So why did I spend a blog entry talking about the end of the legacy IT professional? I want you to think about the above as I cover the legacy and modern provisioning methods available in Azure AD. As we explore the methods, you’ll begin to see the importance programmatic access to cloud solutions will play in this cloud evolution and the opportunities that exist for those IT professionals that are willing to evolve along with it.

In my next post to this series I will cover the various GUI methods available for user provisioning in Azure AD.

Experimenting with the Azure B2B API

Hello all!

On October 31st Microsoft announced the public preview of the Azure B2B Invitation API. Prior to the introduction of the API, the only way to leverage the B2B feature was through the GUI. Given that B2B is Microsoft’s solution to collaboration with trusted partners in Office 365, the lack of the capability to programmatically interact with the feature was very limiting. The feature is now exposed through Azure’s Graph API as documented here.

A friend challenged me to write a script or small application that would leverage the API (Yes we are that nerdy.) Over the past year I’ve written a number of PowerShell scripts that query for information from OneDrive and Azure AD so I felt I would challenge myself by writing a small .NET Forms application. Now I have not done anything significant in the programming realm since freshman year of college so I thought this would be painful. Thankfully I have a copy of Visual Studio that comes with my MSDN subscription. All I can say is wow, development solutions have evolved since the 90s.

I won’t bore you with the amount of Googling and reading on MSDN I did over the weekend. Suffice to say it was a lot. Very tedious but an awesome learning experience. I can see a ton of re-use of the code I came up with for future experiments (even though I’m sure any real developer would point and laugh).

Before I jump into the detail, I want to mention how incredibly helpful Fiddler was in getting this all working and getting a deep dive understanding of how this all works. If you’re interesting in learning the magic of how all this “modern” stuff works, a tool like Fiddler is a must.

First off we need to register the application in Azure AD as a Native App to obtain a Client ID per this article. Next we need to grant the application the delegated right to read and write directory data as described in the MS article introducing the API. Once the application is registered and the rights have been granted, we can hammer out the code.

Before I jump into the code and the Fiddler traces, one thing that caught my eye in the returned json object was an attribute named invitedToGroups. If you’re familiar with the Azure B2B functionality, you’ll recall that as part of the B2B provisioning process, you can add the user object to a group. This is very useful in saving you time from having to do this after the user accepts the invitation and their user objects populates in the Azure AD. What’s odd about this is this attribute isn’t documented in the Microsoft blog I linked above. Digging into the github documentation, it looks like the information about it was removed. Either way, I decided to play around it with, but regardless of whether or not I followed the schema mentioned in the removed Github documentation, I couldn’t get it to take. I am fairly sure I got the schema of the attribute/value pair correctly, so we’ll have to chalk this up to MS playing with feature while the functionality is in public preview.

So let’s take a look at the code of this simple Windows form application, shall we?

In this first section of code, I’m simply pulling some information from the input fields within the forms application.

// Pull data from user input fields
string tenantid = tenant.Text;
string emailaddress = email.Text;
string redirectsite = redirect.Text;
string group = GroupID.Text;

In this new section of code, I’m leveraging functions from the ADAL library to redirect the user to authenticate against Azure AD, obtain an authorization code for the graph API, and submit that code for an access token for the Graph API.

// Authenticate user and obtain access token
AuthenticationContext authcontext = new AuthenticationContext("" + tenantid);
AuthenticationResult token = authcontext.AcquireToken("", clientid, redirectURI, PromptBehavior.Always);

In this section of code I build an instance of the httpclient class that will be used to submit my web request. You’ll notice I’m attaching the bearer access token I obtained in the early step.

// Deliver the access token to the B2B endpoint along with the posting the JWT with the invite information
string URL = "";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Authorization = new
System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.AccessToken);

Here I issue my HTTP request to post to the invitation endpoint and include json object with the necessary information to create an invitation.

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
request.Content = new StringContent("{"invitedUserEmailAddress":"" + emailaddress + "","inviteRedirectUrl":"" + redirectsite + "","sendInvitationMessage":true,"invitedToGroups":[{"group":"" + group + ""}]}", Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(request);

Finally I parse the json object (using the Newtonsoft library) that is returned by the endpoint to check to see whether or not the operation was completed.

string content = await response.Content.ReadAsStringAsync();
Newtonsoft.Json.Linq.JToken json = Newtonsoft.Json.Linq.JObject.Parse(content);
string myresult = json.Value("status");

Quite simple right? It had to be for someone as terrible as developing as I am. Imagine the opportunities for an API like this in the hands of a good developer? The API could be leveraged to automate this whole process in an enterprise identity management tool allowing for self-service for company users who need to collaborate with trusted partners. Crazy cool.

This is the stuff I applaud Microsoft for. They’ve take a cumbersome process, leveraged modern authentication and authorization protocols, provided a very solid collection of libraries, and setup a simple to use API that leverages industry standard methodologies and data formats. Given the scale of cloud and the requirement for automation, simple and robust APIs based upon industry standards are hugely important to the success of a public cloud provider.

This whole process was an amazing learning experience where I had an opportunity to do something I’ve never done before and mess with technologies that are very much cutting edge. Opportunities like this to challenge myself and problem solve out of my comfort zone are exactly why I love IT.

I hope the above post has been helpful and I can’t wait to see how this feature pans out when it goes GA!

Feel free to reach out if you’re interested in a copy of my terrible app.


Deep Dive Into Resource-Based Constrained Delegation – Part 2

In this post we’ll dive right into the weeds. To demonstrate how RBKCD works I built an environment in my Azure lab with the following properties:

  1. Two Active Directory forests named contoso.local and fabrikam.local.
  2. Two-way Active Directory forest trust between the two forests.
  3. Server configuration
    • SERVER12.CONTOSO.LOCAL (Windows Server 2012 R2) – AD DS
    • SERVER13.CONTOSO.LOCAL (Windows Server 2012 R2) – IIS
    • SERVER14.FABRIKAM.LOCAL (Windows Server 2012 R2) – AD DS
    • SERVER15.FABRIKAM.LOCAL (Windows Server 2012 R2) – File Server

We’ll be using a web application developed by Brian Murphy Booth named DelegConfig. The application is a bit dated, but will serve our purpose in testing RBKCD. You can download a copy from here.

On SERVER13 we’ll be adding the application to IIS and running it under the Default Application Pool for simplicity sake. We’ll use the application to access an SMB share on SERVER15 and we’ll be accessing the application from a web browser on SERVER12.

The SMB share has had the share permissions configured so that the mfelton user account has read permissions on the share. SERVER13 has not been configured for any type of delegation. Let’s see what happens when we attempt to access the share via the web application. We’ll use Microsoft Network Monitor running on SERVER13 to perform a packet capture and examine the authentication exchanges.

The first Kerberos exchange we see is performed in the two frames below.


Let’s dig into frame 45 and look more deeply at the request. In the image below we that SERVER13 is obtaining a service ticket for itself on behalf on the mfelton user as detailed in this link. SERVER13 will use this ticket to request additional tickets for the user mfelton in order to access SERVER15.


The next Kerberos exchange is performed in these two frames.


Here we have SERVER13 requesting a Kerberos ticket for the CIFS share on SERVER15 on behalf of the user mfelton. If we dig into the PaData of the request we see that the PA-PAC-OPTIONS are included. Although I’m unable to find a way to enumerate the bits, contained in the PAC-OPTIONS are a bit that says resource-based constrained delegation is supported by the client (more detail in this link). Since this is a Windows Server 2012 or later DC, the DC supports resource-based constrained delegation and supplied the application with a ticket it can use to access the FABRIKAM domain.


In the third exchange the application delivers the ticket it received from the CONTOSO domain and requests a ticket for SERVER15 on behalf of the user mfelton.

But wait, is that a KDC_ERR_BADOPTION we see? Well one thing you’ll notice I never did was configure resource-based constrained delegation and I receive the expected error as outlined in this link. So let’s remedy that and look at the differences.

First off, the eternal question, how do we configure resource-based constrained delegation? Well it’s a simple two liner depending on whether or not you’re configuring it on a user or computer account. In our scenario it is the following:

$Computer = Get-ADComputer -Identity SERVER13
Set-ADComputer -Identity SERVER15 -PrincipalsAllowedToDelegateToAccount $Computer

The first two exchanges look exactly the same as the previous example:


The third exchange is where see a difference:


Here we see we are successfully able to obtain a ticket to the SMB share on SERVER15 successfully impersonating the mfelton user account as seen in the frame below.


That’s all there is to it to enable a pretty neat feature in the legacy authentication protocol realm. Hopefully these posts have helped you better understand the feature and how it works. If anything, this series will point to the right articles where you can read more about it.