Search code examples
c#asp.net-web-apiasp.net-identity

How to implement AuthorizationContext attribute on WebApi?


I'm trying to implement password expiry policy and found a good blog showing an example - but that is in MVC. I'm trying to implement it for WebApi2. I expected WebApi to have similar functionality but so far have failed to locate the right namespaces / methods to call.

Relevant part of the code:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    if (!filterContext.ActionDescriptor.IsDefined(typeof(SkipPasswordExpirationCheckAttribute), inherit: true)
        && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(SkipPasswordExpirationCheckAttribute), inherit: true))
        {
            ...

            if (timeSpan.Days >= _maxPasswordAgeInDay)
            {
                ...

                filterContext.HttpContext.Response.Redirect(urlHelper.Action("ChangePassword", "Account", new { reason = "passwordExpired" }));
            }
        }

    base.OnAuthorization(filterContext);
}
  1. On WebApi, the override method signature is OnAuthorization(HttpActionContext actionContext) instead of (AuthorizationContext filterContext) - how do I check for SkipPasswordExpirationAttribute using actionContext?

  2. Once I decide the password has expired, what action should I take? I don't suppose I can "redirect" user from WebApi as that doesn't make any sense.


Solution

  • Use the ActionDescriptor or ControllerContext properties to look for the attribute you want.

    Here is an example of how to check for SkipPasswordExpirationAttribute.

    public override void OnAuthorization(HttpActionContext actionContext) {
        var attribute = actionContext.ActionDescriptor.GetCustomAttributes<SkipPasswordExpirationAttribute >(true).FirstOrDefault();
        if (attribute != null)
            return;
        //You have access to the Request and Response as well.
        var request = actionContext.Request;
        var response = actionContext.Response;
    
        //...Once you decide the password has expired, 
        //update the response with an appropriate status code 
        //and response message that would make sense 
        //to the client that made the request
        response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
        response.ReasonPhrase = "Password expired";
    
        base.OnAuthorization(actionContext);
    }