user8512043
user8512043

Reputation: 1157

Action Filter Unable To Block An Unauthorized Request in Controller

I am trying to block a request in controller if it doesn't have a specific value in header. So I did the following using some guidelines:

public class InvalidTokenAttribute : Attribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        var Authorization = context.HttpContext.Request.Headers["test"];

        if (Authorization != "12345678910")
        {
            context.ModelState.AddModelError("Authorization", "Authorization failed!");
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        
    }
} 

It worked and confirmed when I use the attribute in a specific controller putting Console.WriteLine() in the custom attribute class. But unfortunately it doesn't throw any exception in the controller level. I did something as follows:

Request:

GET http://localhost:PortNo/WeatherForecast/GetAllTeams
test: "12345678"

Controller:

[HttpGet]
[InvalidToken]
public async Task<ActionResult<IEnumerable<TeamDetails>>> GetAllTeams()
{
    string Token = Request.Headers["test"];
  
    return Ok(Token);
}

With the attribute, it shouldn't get into the controller as the header value is invalid or mismatched. Unfortunately value returned in the controller and shows output. Is there anything that I missed?

Upvotes: 0

Views: 941

Answers (1)

Xinran Shen
Xinran Shen

Reputation: 9993

When Authorization != "12345678910" , your action filter just add a ModelError, it will not Interrupt request . So ,If you don’t want it get into the controller,you can add some code like:

Filter

public class InvalidTokenAttribute : Attribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        var Authorization = context.HttpContext.Request.Headers["test"];

        if (Authorization != "12345678910")
        {
            context.ModelState.AddModelError("Authorization", "Authorization failed!");
            //you can add this code to Interrupt request,So request will not get into controller
            context.Result = new BadRequestObjectResult(context.ModelState);
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        
    }
} 

enter image description here

Upvotes: 2

Related Questions