There is plenty of content on the internet that shows you how to use ASP.NET Core Authentication pipeline to protect a Web API with Azure Active Directory.  This is all working great except when your Web API returns a 401 Unauthorized error without providing much information.  You can end up spending a lot of time, pulling your hair out trying to figure out what can go wrong even though you (or at least believe) have followed every step of the documentation, implemented all the best practices and guidelines.  Hopefully, this blog can help alleviate that pain for you.  I will build the content here on top of my previous blog post which discusses how you can protect your Web API with Azure Active Directory.

Let’s dig in…

When you use the [Authorize] attribute to protect your web API controller as followed

or to protect an action in the controller

It expects the request has a valid Bearer token presented in the “Authorization: Bearer ey…” HTTP Request header.  The controller returns a 401 Unauthorized response when the request either does not have an “Authorization Bearer token” header or the request contains an invalid Bearer token (the token is expired, the token is for a different resource, or the token’s claims do not satisfy at least one of the application’s token validation criteria as defined in the JwtBearerOptions’s TokenValidationParameters class).

The JwtBearerEvents class has the following callback properties (invoked in the following order) that can help us debug these 401 Access Denied or UnAuthorization issues:

  1. OnMessageRecieved – gets called first for every request
  2. OnAuthenticationFailed – gets called when the token does not pass the application’s token validation criteria.
  3. OnChallenge – this gets called last before a 401 response is returned

Note:  In some scenarios, the OnAuthenticationFailed method may not be invoked, for example:  the request does not have any bearer token or it contains a malformed token (invalid jwt token format)

We will use the above callbacks to build our own custom error message to return to the client.

Note:  the sample code in this blog is only meant for Proof of Concept and can review PII information only for debugging local development effort so you should be cautious not to use in production environment.

Implement the following code:

  1. Enable PII logging (it’s off by default) in the Configure method in Startup.cs file:
  1. Create a method called FlattenException to format our Exception Message
  1. Implement the above callbacks in the ConfigureServices method in Startup.cs file

For completeness, I have also implemented the OnTokenValidated property to print out the token claims. This method is invoked when the authentication is successful.

Here is my entire Startup.cs file

The result…

The above implementation should result in 401 Error message with some output as followed

or the following

Leave a Reply

avatar
  Subscribe  
Notify of