UseWindowsAzureActiveDirectoryBearerAuthentication v’s UseJwtBearerAuthentication for Authorization with Azure Active Directory for an ASP.NET Web API

In my previous post, Securing a Web API using Azure Active Directory and OWIN, I covered how to authorize requests against Azure Active Directory using the UseWindowsAzureActiveDirectoryBearerAuthentication extension method in the OWN startup class. This extension method has been designed specifically for Azure Active Directory but if you think about it, the Authorization token is just a JWT token, so in theory you could take a much more generic approach to authorizing access by validating the JWT. This can be done using the UseJwtBearerAuthentication extension method.

There are a couple of steps to using the UseJwtBearerAuthentication extension method. Firstly, in order to validate the signature of the JWT, we’re going to need the public certificate that matches the key identifier contained in the JWT. In my post on Verifying Azure Active Directory JWT Tokens I cover how to examine the JWT using in order to retrieve the kid, retrieve the openid configuration, locate the jwks uri, retrieve the keys and save out the key as a certificate. In the post I used the certificate (ie wrapping the raw key in —BEGIN—, —END— markers) to validate the JWT; in this case I’ve copied the contents into a text file which I’ve named azure.cer and added it to the root of my web project (making sure the build action is set to Content so it is deployed with the website).

The next thing to do is to remove the UseWindowsAzureActiveDirectoryBearerAuthentication extension method, replacing it with the following code.

var fileName = HostingEnvironment.MapPath(“~/”) + “azure.cer”;
var cert = new X509Certificate2(fileName);
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
    AllowedAudiences = new[] {ConfigurationManager.AppSettings[“ida:Audience”]},
    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        new X509CertificateSecurityTokenProvider(ConfigurationManager.AppSettings[“ida:IssuerName”], cert)

This code uses the azure.cer certificate file combined with the Audience and IssuerName which I’ve added to the web.config.

<add key=”ida:Audience” value=”a07aa09e-21b9-4e86-b269-a18903b5fe54″ />
<add key=”ida:IssuerName” value=”” />

The Audience is the application id (aka client id) of the Azure application registration. The IssuerName needs to match to what appears in the JWT. Opening one of the tokens in it’s the ISS value that you want to use as the IssuerName.

Now you can run the project and see that again the requests are validated to ensure they’re correctly signed.

Leave a comment