I have app.net 4.5 web api working using owin. Whenever an unauthorized request is made, it returns 401 with the following response, as expected:
{"Message":"Authorization has been denied for this request."}
I would like to add additional information to this answer (expired token, invalid role, etc.) and implemented custom [AuthorizeAttribute] based on SO post .
public class MyAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { var response = actionContext.Request.CreateResponse<MyError> (new MyError() { Description = "This is why you're unauthorized" }); response.StatusCode = HttpStatusCode.Unauthorized; actionContext.Response = response; } }
and then used it on my controllers, for example:
[MyAuthorizeAttribute(Roles = "Foo")] public class MyController : ApiController { ... }
which returns 401 with the following response as expected:
{"Description": "This is why you're unauthorized"}
However, I donโt see how to determine the reason the request was unauthorized from the HttpActionContext passed to MyAuthorizeAttribute.HandleUnauthorizedRequest . For example, when I debug locally and make a request with an expired token, it throws an IDX10223: Lifetime validation failed. The token is expired. ValidTo: '...' Current time: '...'. explanation to SecurityTokenExpiredException IDX10223: Lifetime validation failed. The token is expired. ValidTo: '...' Current time: '...'. IDX10223: Lifetime validation failed. The token is expired. ValidTo: '...' Current time: '...'. or with an invalid audience, it throws a SecurityTokenInvalidAudienceException explanation of Message=IDX10214: Audience validation failed. Audiences: '...'. Did not match: validationParameters.ValidAudience: 'null' or validationParameters.ValidAudiences: '...'. Message=IDX10214: Audience validation failed. Audiences: '...'. Did not match: validationParameters.ValidAudience: 'null' or validationParameters.ValidAudiences: '...'. . I set some breakpoints in my Startup.cs before they could even catch one of these exceptions before they were thrown.
How to determine the specific reason why the request is unauthorized using owin middleware?
Greg
source share