Is this an acceptable implementation of a custom bearer token authorization mechanism?
Authorization Attribute
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();
}
}
Validation Service. APISettings class is used in appSettings, but validation can be extended to use a database ... obviously :)
public class APISettings
{
public string Key { get; set; }
}
public class ValidateBearerToken : IValidateBearerToken
{
private readonly APISettings _bearer;
public ValidateBearerToken(IOptions<APISettings> bearer)
{
_bearer = bearer.Value;
}
public bool Validate(string bearer)
{
return (bearer.Equals($"Bearer {_bearer.Key}"));
}
}
Implementation
[Produces("application/json")]
[Route("api/my")]
[Authorize]
public class MyController : Controller
appSettings
"APISettings": {
"Key": "372F78BC6B66F3CEAF705FE57A91F369A5BE956692A4DA7DE16CAD71113CF046"
}
Request Header
Authorization: Bearer 372F78BC6B66F3CEAF705FE57A91F369A5BE956692A4DA7DE16CAD71113CF046