JWT AutorizationAttribute

Hello
So I recently ran into a project where I wanted to use JSON Web Token for authorization. Since I at that point did'nt realize that there are two default implementations of the "AuthorizeAttribute" class, it took some time - It turned out that it's implemented in the following classes:

  • System.Web.Mvc.Filter.AuthorizeAttribute
  • System.Web.Http.AuthorizeAttribute

If you want to make a custom authorization attribute and use it in an MVC Controller you should inherit from the .Mvc.FilterAuthorizeAttribute class, but if you on the other hand want to use it in webapi you should go with .Http.AuthorizeAttribute

Just for show here is the one I ended up using in the first iteration of my app:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class JwtAuthenticationAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var authorizationHeader = actionContext.Request.Headers.Authorization?.ToString();
        if (!string.IsNullOrEmpty(authorizationHeader)) {
            var secretKey = ConfigurationManager.AppSettings.Get("secret");
            try
            {
                var jsonPayload = JWT.JsonWebToken.Decode(authorizationHeader, secretKey);
                return true;
            }
            catch (JWT.SignatureVerificationException)
            {
                return false;
            }
        }
    return false;
}

Btw. I use the Nuget JWT by Alexander Batishchev