1

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!

2
  • 1
    It's awkward to first let request through and check auth after request is finished... Can you please clarify why you decided to do that? Commented Sep 13, 2020 at 22:57
  • I didn't know that's what I was doing at the time. It's not supposed to do that. Commented Sep 15, 2020 at 0:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I'll try this out and post an update.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.