Using Azure Active Directory in Azure Government and Azure Commercial to Authenticate users to your ASP.NET Web Application
Like all of Azure Government the instance of Azure Active Directory that it uses is isolated from the one running in Azure Commercial. The AAD team has a detailed article on how to setup your ASP.NET Web Application with AAD on Commercial here. You can use the steps as outlined in that article to connect a Web Application running in Azure Government to an AAD instance running in Azure Commercial or Azure Government. (TIP: I prefer to get a simple working example by using the file new project wizard in visual studio and selecting “work or school” account as your authentication mechanism.)
However, what if you want your application to be able to use both? Easy!
- Using the instructions above get it working against Azure Commercial.
- Create the application in the Azure Government portal, just like you did in commercial
- Add a second set of keys to your web.config for your Gov AAD application entry (ClientID, AADInstance endpoint, and TenantID)
- In your Startup.Auth.cs file you will need to add a second OpenIDConnection, and set the AuthenticationType for each. You can see in my example that I have the authentication type set to AADC for commercial and AADG for government Azure.
- If you are building a single tenant application where all users must be in your AAD tenant than use this code:
- If you are building a multi-tenant application where a user can exist in ANY Azure Gov or Commercial tenant than use this code (and don’t forget to set the flag in the portal to tell AAD that your application is multi-tenant):
- Tweak your Account controller to handle the multiple authentication types.
- Alter the SignIn Method to take in the auth type on the query string
- Pass the auth type along on the call back URI query string
- On call back, stash the auth type somewhere, in my example I use ASP.NET Session State but you will probably want to use something a bit more scalable.
- On SignOut grab the auth type we stashed, and pass it to the SignOut command.
- The account controller should look like this now:
- Provide a UI for the user to tell you what directory they want to log into. I did that in my _LoginPartial.cshtml. Here is mine:
Get the full source code here.
The final application will look like this. NOTE: In my sample I put the choice of login with Gov/Commercial AAD on the user, however in a real world application you probably know that before hand and can automatically direct the user to the right AD based on the URL the user went to or by asking them for their user name.