Reputation: 11
I'm creating a custom attribute in dotnet that is supposed to check the authorization header. If it is the same as some hard coded string it is supposed to pass but else the user should not be able to use the specified route.
I think I'm getting the response header correctly but I'm not sure how to send a HTTP response if it fails.
public class CustomAuthorization : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
var httpContext = context.HttpContext;
string authHeader = httpContext.Request.Headers["Authorization"];
if(authHeader == "Kawaii")
{
return;
//do nothing cause its fine
}
else
{
httpContext.Response.WriteAsync("The authorization header was incorrect, is should be Kawaii");
}
}
}
Any help would be greatly appreciated!
Upvotes: 1
Views: 668
Reputation: 8691
From what you've described, it sounds like you should be using OnActionExecuting
instead of OnActionExecuted
. Within the body, instead of writing to context.HttpContext.Response
, you set context.Result
to an ActionResult representing the response
public class CustomAuthorization : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
string authHeader = context.HttpContext.Request.Headers["Authorization"];
if(authHeader == "Kawaii")
return;
context.Result = new UnauthorizedResult();
}
}
However, this approach sounds like a better fit for an AuthorizationFilter instead of an ActionFilter. Have a look at the filter pipeline documentation for a list of the different types of filters and what they do.
Upvotes: 2