Category: Active Directory

App Service Easy Auth with Auth0 (or any Open ID Connect provider)

So I’m going to prefix this with a warning – I doubt this is officially supported but at a basic level it does seem to work. I would use at your peril and I’m writing this in the hope that it makes for a useful starting point discussion with the App Service team.

I was looking at Easy Auth this week and found myself curious as to if it would work with a generic Open ID Connect identity provider. My first choice provider is Auth0 but that’s not one of the listed providers on the Easy Auth configuration page which, on the face of it, is quite limited:

Azure AD is (as well as many other things) an Open ID Connect Provider so I had a look at its settings in the advanced tab and its asking for two pretty common pieces of information in the identity world: a client ID and an issuer URL. I had an app in Auth0 that I use for general testing so I pasted in its well known configuration endpoint and the ID for my client:

I hit save and it seemed to accept everything. My web app is sat on the URL https://jdreasyauth0.azurewebsites.net/ so on the Auth0 side I added a callback URL to the Easy Auth callback endpoint:

Easy Auth forwards on the contents of common claims in headers such as X-MS-CLIENT-PRINCIPAL-ID (the subject) and X-MS-CLIENT-PRINCIPAL-NAME (the name) so to see if this was working I uploaded a simple ASP.Net Core app that would output the contents of the request headers to a web page. Then I paid it a visit in my browser:

Oh. So that’s hurdle one passed. It does redirect successfully to a none-Azure AD identity provider. What about logging in?

Great. Yes. This works too. And the headers are correct based on the identity I used to login with.

How does this compare to the headers from an Azure AD backed Easy Auth:

Basically the Auth0 login is missing the refresh token (I did later set a client secret and tweak configuration in Auth0) – so there might be some work needed there. But I don’t think that’s essential.

It would be incredibly useful to be able to use Easy Auth in a supported manner with other identity providers – particularly for Azure Functions where dealing with token level authorization is a bit more “low level” than in a fully fledged framework like ASP .Net Core (though my Function Monkey library can help with this) and is only dealt with after a function invocation.

Multi-Tenanted Authentication with Azure AD and Office 365 (and IdentityServer3)

With solutions such as Azure AD and Office 365 becoming more common as a source of an organisations identity on the Internet it can be useful to have an application offer authentication against them. As a typical scenario let’s imagine you’ve developed a time tracking SaaS solution and you have a number of customers who wants to use it but logon with their Office 365 identities.

It’s a bit of a lengthy process but not difficult to do when you know how and hopefully by way of this worked example I can show you how to add this functionality yourself.

As it’s fairly commonplace to want to offer other external identities alongside Office 365 I’m going to integrate this into the excellent IdentityServer3 OpenID Connect Provider however nothing here really depends on IdentityServer3 and if you’ve got a basic familiarity with OWIN it should be fairly obvious how to decouple what I’ve done here.

The source code for all the below can be found in GitHub.

Setup the Visual Studio Project

Firstly open up Visual Studio (I’m using 2015) and create a new ASP.Net Web Application. In the New ASP.Net Project dialog select to build an MVC application and ensure that the authentication method is set to No Authentication:

1

Now you need to add a set of NuGet packages to the project:

Install-Package Thinktecture.IdentityServer3
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Security.OpenIdConnect

Now in the properties pane for the project enable SSL and note the port number:

2

And in the project properties (I love how this is spread liberally about the place!) set the start page to be the https site:

3

Now add a class called Startup to the root of the project as below. As we’ve added the Microsoft.Owin.Host.SystemWeb package it’s going to look for this on startup and will throw an exception if it can’t find it – we’ll fill it in later.

4

 

Now add the following to your web.config file:

15

 

At this point you should be able to run your solution and the boilerplate MVC website should appear secured with a self signed SSL certificate generated by Visual Studio.

Setup an Azure AD

We’re going to use two domains for the following – one for our application to authenticate against and federate against other directories and a second domain that we’re going to use to login with.

If you’ve got an Azure subscription you should already have a default domain so we’ll use that for logging in.

To enable the multi-tenanted scenario create a second Azure AD in the (old) management portal. This AD is used to host an Azure AD Application and handles the federation between the other domains.

Go to the Applications tab for your directory and add an application, select “Add an application my organisation is developing”. Give the application and appropriate customer facing name (they will be able to see this in their own domain configuration and during sign up) and set this to be a web application:

5

In the next page set the sign on URL to be based on the the root of your web project (as you noted earlier) extended with the path /identity/signin-azuread giving you a URL such as:

https://localhost:44300/identity/signin-azuread

In the second box you need to set a unique URI for your application. The best way to do this is based on your own domain in the form http://mydomain.onmicrosoft.com/myapplication:

6

Azure will now whirr away for a second or two before showing you the application dashboard. Click the configure tab. Move down to the middle of the page and set Application is Multi-Tenant to on and create a new key. Then hit save. The key will display after you’ve hit save. Note down both the key and the client ID as you will need them later.

7

Configure IdentityServer3 and Azure AD / Office 365 as an Identity Provider

Back in Visual Studio edit the Startup class we created earlier. Firstly add a folder to the root of the project called Configuration, download the IdentityServer3 test certificate, and add it to this folder setting it to Copy if Newer in the properties panel:

8

IdentityServer3 will use this certificate (when configured below) to sign the tokens it issues however it’s important to be clear that in a production environment this certificate needs to be generated and kept securely. The certificate used here is a certificate used in the IdentityServer3 tests and stored / loaded in a manner designed for brevity in the source code rather than security. In a production environment you’d keep this in your certificate store.

Now configure IdentityServer3 as an endpoint within this solution by adding the following to the Startup class:

9

We’ve set IdentityServer3 up to use it’s in memory stores and created a client that we’ll later authenticate against (see the IdentityServer3 docs for more details on this).

We now need to configure Azure AD / Office 365 as an identity provider by filling in the ConfigureIdentityProviders method:

10

It’s vital that the client ID and redirect URI supplied to the Open ID Connect options exactly match those in the Azure AD application you created earlier and the Authority string must look exactly as written here including the trailing /.

As this point things will build but there’s nothing in our solution requiring authorization however you can navigate to the published configuration endpoint and should see some json describing our service. My endpoint is at:

https://localhost:44300/identity/.well-known/openid-configuration

Authorizing and Viewing Claims

We’re going to use an Authorize attribute on an MVC action to test our work so far. To begin with we need to get our MVC project to use the token end point we’ve created above. We need to add the following to the bottom of our Configuration method:

11

You need to ensure you use the port your website is running on on your development machine. Mine is on 44300.

Modify the About action in HomeController.cs to look like the following:

12

And the corresponding View to:

13

Now run the project and if you’ve got all the magic numbers and URLs right you should be navigated to the Azure AD logon page:

14

Login using a different AD to the one we set up earlier and if you now login you should end up back at the about page with a set of claims showing:

16

If you now head back into the Azure Management Portal and inspect the Applications tab for the Azure AD you used to login with you should find that the application we created earlier has been added here:

17

If all that worked then great – that’s the happy, easy, path dealt with! If not I suggest checking out my number one tip for dealing with IdentityServer3 issues.

The Administrator Consent Workflow

Depending on your domain configuration (the one you logged in with) then you might have hit the error page shown below:

18

Many domains, particularly of larger organisations, will have enabled Administrator Consent. This prevents users from being able to use their domain account to access resources they are not authorized to – unfortunately the error above isn’t very useful to end users.

To allow users in a domain configured this way to be able to access your application you need to implement a workflow that allows the Administrator to grant consent for users. Before continuing, if you’ve followed the steps above, then in Azure delete the application from your login domain – select it in the management portal and click Manage Access, then click Remove Access.

Firstly let’s turn on Administrator Consent in our login domain – select the domain in the management portal and click the Configure tab. When Azure has finished whirring away scroll down to the Integrated Applications section and set “USERS MAY GIVE APPLICATIONS PERMISSION TO ACCESS THEIR DATA” and “USERS MAY ADD INTEGRATED APPLICATIONS” to no. Then press save.

19

Now in the users section of your domain add a new user and give them only the User role:

20

Next head back to the Azure AD application we created at the start of this post, click the Configure tab and scroll down to the single sign on section. Enter a URL for the root of your website and click save:

24

Ensure the browser is closed and if you now run the Visual Studio solution again and attempt to login with this new user then you should see the error message shown earlier. If not check the configuration in Azure once more.

At this point we’ve got a domain that requires administrator consent for users to attach to our application. Begin by adding a new Nuget package:

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory

Then add a class called AzureTenant as shown below:

21

We now need to be able to manage our tenants. Normally you’d use some form of persistent store for this but I’m going to use a very basic in memory service by way of an example. The full service code is in GitHub here however there are two important sections. Firstly our controller (which we’ll work on later) will create a temporary tenant before handing off to Azure and later on after association is complete we convert this to a permanent tenant. This two stage process can be useful as in a more realistic example you may want to track some additional state across this request however all you need is someway of attaching data to a persistent unique ID – reusing the tenant like this keeps the example simple. However this code can be seen below:

25

When our controller hands off to Azure to handle the domain association we need to do so by forming up a URL and doing this can be seen below:

26

And finally following the association we need to retrieve the tenant ID for the newly associated tenant (and this is where your client key created at the beginning of this piece is required):

Now we need to add an MVC controller that is going to present this functionality to the user. There is some boilerplate at the bottom but I want to focus here on the AdminConsent and Associate methods as shown below:

22

The default admin consent view presents a button to the user and a paragraph confirming what they are about to do – when the post back hits the controller it does two things. Firstly it creates a temporary tenant in our data store and then redirects to the Azure authorization endpoint using the temporary ID of the tenant as the state.

When the user confirms the association in the Azure AD management page presented during the redirect then it will call back to the Associate action passing in the temporary tenant ID as the state. In more complex examples tracking the state in this way allows us to track back the Azure request to any information we’ve gathered before confirmation. The Associate action then uses our in memory service to confirm the association and handles the routing off to the appropriate page based on success or failure.

Finally having done all of the above we’re going to put a link to our admin consent page on the home page. I modified the Jumbotron to point at the AdminConsent view.

At this point you should be able to run the solution (and this is the complete solution in GitHub) and if things are wired up correctly then you should be able to click your admin consent link. Try this with your test user and it will fail but if you then try it with your admin user you should see a screen like this:

23

However if you’ve got everything right you should end up back at the success screen on your website and can now navigate into the About section.

Hopefully that helps anyone trying to figure out how to do this themselves and feel free to ask me questions in the comments or on Twitter.

Finally, worth repeating – the code is all available on GitHub.

Authenticating an AngularJS Single Page Application with Azure AD

I’ve been spending a lot of time in Angular JS of late with Web API serving up the data. Generally I’ve been authenticating with what Microsoft call “individual accounts” – usernames and passwords stored by the web service or through common logins such as Microsoft Accounts, Facebook etc.

However recently I had the need to authenticate such a pairing against Azure AD.

I must admit I expected a day or two of pain followed by a lengthy blog post but to my very pleasant surprise Microsoft have recently released a preview version of a JavaScript library and AngularJS module for doing just this.

The steps to take in Angular and AD are well documented on the GitHub page that you can find here.

Azure AD, Groups, Roles and the Authorize Attribute

Configuring a new MVC 5 website to authenticate against an Azure Active Directory is really simple – all you need to do is configure using the ASP.Net 4.5 Web Application creation wizard when you create a new project as described here.

If you complete that successfully and add an Authorize attribute to one of your controllers or actions then you’ll find everything works as you’d expect.

However if you try and use roles with AD groups (obvious thing to try right – particularly now groups are exposed in the management portal) you’ll find you get UnauthorizedException’s being thrown. This is because, out of the box, the current implementation doesn’t translate group memberships into role claims.

Fortunately this is fairly straightforward to resolve by supplying a specialization of the System.Security.Claims.ClaimsAuthenticationManager class to ASP.Net and using the Azure AD Graph API to retrieve the memberships of the authenticated user.

The good news is I’ve done the grunt work for you and extended the NuGet package I blogged about recently to include an implementation of a claims authentication manager that does just this. You can take a look at the code involved here. It makes use of the Windows AD Graph API Helper Library posted on MSDN which takes care of some of the required service wrapping.

As before the source for the whole library is in GitHub and covered by the MIT license and a NuGet package is available.

In order for you to use AD groups as roles then your application is going to need to be able to read data from your Azure AD and to allow that you’ll need to do some additional configuration of your application inside the Azure Management Portal. The New Project wizard will have added your website to your Active Directory which you can see in the Management Portal on the Applications page. You can see mine listed below:

adstep1

Select your application and you’ll be taken to the application configuration page which should look something like the below:

adstep2

To configure your app you need to tap the Manage Access button down the bottom. Do that and then select Change the directory access for this app. Then on the next page select Single sign on, read directory data.

Azure will whirr away for a short while changing settings on your AD and when it’s done you need to go to the Configure tab (click configure at the top of the page as shown in the image above). In here you need to create a key that your application can use to authenticate with the Graph API and read AD data.

To do this scroll down to the Keys section and click the drop down and choose whether you want a 1 year or 2 year key. In the screenshot below I’ve picked 1 year.

adstep3

After you’ve done this click save in the toolbar at the bottom and you’ll see your key.

We’ve just about done in the Azure Management Portal all you need to do before you leave is take note of the Client ID and the Key as shown in the image below (mine are blurred out!).

adstep4

For the rest of this walkthrough I’m assuming you’re configuring a web site rather than an Azure Web Role but the claims manager we are using uses the Azure Configuration Manager for both so if you are using  a Web Role you can simply put the settings in your .cscfg and .csdef files.

Firstly add the NuGet package to your project which you can do in the Package Manager GUI or in the console:

Install-Package accidentalfish.aspnet.identity.azure

Then you need to edit your web.config file with a couple of app settings. For this you need your Client ID and Key that you noted down earlier.

adstep5

The RoleClaimIssuer is optional but is the claim issuer you want inserted into the claim, if you leave this out the issuer will be set as DefaultRoleIssuer.

The final step you need to take is to tell the ASP.Net identity model about the claims manager. To do this locate the <system.identitymodel> section of the web.config file and insert the line highlighted below at the bottom:

adstep6

To save you some typing the line to paste is:

<claimsAuthenticationManager type="AccidentalFish.AspNet.Identity.Azure.GraphRoleClaimsAuthenticationManager, AccidentalFish.AspNet.Identity.Azure"/>

With that you’re done. You can use the groups you’ve configured in the Azure AD as roles with the [Authorize(Roles=”…”)] attribute.

I hope all this is useful, if you have any feedback then please do get in touch.

Contact

  • If you're looking for help with C#, .NET, Azure, Architecture, or would simply value an independent opinion then please get in touch here or over on Twitter.

Recent Posts

Recent Tweets

Invalid or expired token.

Recent Comments

Archives

Categories

Meta

GiottoPress by Enrique Chavez