Creating custom Action Filter for Authorization in .net Core Api

Viewed 437

I am creating an custom action filter in which I am trying to check if there is a key ‘Authorization’ in the request header or not. If it is there, whether it contains a value ‘Bearer’ or not. I tried something like this::

public class CustomAuthFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string data;
            var x=filterContext.HttpContext.Request.Headers.TryGetValue("Authorization",out data);
            //what to do here
        }
    }

How do I do this?

1 Answers

To cover up your simple scenario you can do something like this:

public class CustomAuthFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool result = filterContext.HttpContext.Request.Headers.TryGetValue("Authorization", out var token);

        if (!result)
        {
            filterContext.Result = new UnauthorizedObjectResult("Missing authorization header");

            return;
        }

        if (!token.Contains("Bearer "))
        {
            filterContext.Result = new UnauthorizedObjectResult("Invalid bearer token");

            return;
        }
    }
}
Related