title: Custom Bearer Token Authorization for ASP.Net Core
body: <p>Is this an acceptable implementation of a custom bearer token authorization mechanism? </p>
  
  <p><strong>Authorization Attribute</strong></p>
  
  <pre><code>public class AuthorizeAttribute : TypeFilterAttribute
  {
      public AuthorizeAttribute(): base(typeof(AuthorizeActionFilter)){}
  }
  
  public class AuthorizeActionFilter : IAsyncActionFilter
  {
      private readonly IValidateBearerToken _authToken;
      public AuthorizeActionFilter(IValidateBearerToken authToken)
      {
          _authToken = authToken;
      }
  
      public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
      {
          const string AUTHKEY = "authorization";
          var headers = context.HttpContext.Request.Headers;
          if (headers.ContainsKey(AUTHKEY))
          {
              bool isAuthorized = _authToken.Validate(headers[AUTHKEY]);
              if (!isAuthorized)
                  context.Result = new UnauthorizedResult();
              else
                  await next();
          }
          else
              context.Result = new UnauthorizedResult();
      }
  }
  </code></pre>
  
  <p><strong>Validation Service. APISettings class is used in appSettings, but validation can be extended to use a database ... obviously :)</strong></p>
  
  <pre><code>public class APISettings
  {
      public string Key { get; set; }
  }
  
  public class ValidateBearerToken : IValidateBearerToken
  {
      private readonly APISettings _bearer;
  
      public ValidateBearerToken(IOptions&lt;APISettings&gt; bearer)
      {
          _bearer = bearer.Value;
      }
  
      public bool Validate(string bearer)
      {
          return (bearer.Equals($"Bearer {_bearer.Key}"));
      }
  }
  </code></pre>
  
  <p><strong>Implementation</strong></p>
  
  <pre><code>[Produces("application/json")]
  [Route("api/my")]
  [Authorize]
  public class MyController : Controller
  </code></pre>
  
  <p><strong>appSettings</strong></p>
  
  <pre><code>"APISettings": {
  "Key": "372F78BC6B66F3CEAF705FE57A91F369A5BE956692A4DA7DE16CAD71113CF046"
  </code></pre>
  
  <p>}</p>
  
  <p><strong>Request Header</strong></p>
  
  <pre><code>Authorization: Bearer 372F78BC6B66F3CEAF705FE57A91F369A5BE956692A4DA7DE16CAD71113CF046
  </code></pre>