1

I have two different types of JWTs that my .Net Core 3.1 Web API service can use to authenticate.

The service operations of my controller sometimes require that one or both are present. Sometimes they can be called by anyone (without either JWT).

The only attribute I can see that I can apply to a service operation in my controller is the Authorize attribute. I have looked into use that attribute (or a custom one), but I am running in to problems.

It seems that the Authorize attribute cannot change the HTTP Status Code that is returned. In my case, if my service is called without the valid JWT, I need to return a 401 Http Status Code.

How can I conditionally require a service operation in my controller to require authentication and return a 401?

Vaccano
  • 78,325
  • 149
  • 468
  • 850

1 Answers1

1

This is a bit strange because the default status code returned by an authorization failure using the Authorize attribute is a 401. What status code is it returning?

For dealing with multiple JWT tokens, you may want to look at this answer: Use multiple JWT Bearer Authentication

Basically you are setting up multiple authentication schemes and using AddJwtBearer multiple times in the setup. Then you can create multiple Auth policies to cover each combination of requires, one for only the first JWT, one for the second and one for when both are required together (3 total). Then just add the [Authorize(Policy = "PolicyName")] attribute to each endpoint you want to protect depending on the requirements of that endpoint (one or both tokens). For endpoints that don't require a token, just change it to the [AllowAnonymous] attribute.

Bryan Lewis
  • 5,629
  • 4
  • 39
  • 45
  • I have setup my code exactly like you indicated. I was driven to crazy frustration because using `[Authorize(Policy = "PolicyName")]` blocks the call if the policy is not met, but the status code returned is 200 (OK). I have tried everything I can think of to change the code to something else, but no matter where I change it, it always returns as 200. – Vaccano Aug 21 '20 at 00:07
  • If I supply neither of the JWTs, then I will get a 401 (set by the normal Authenticate code). But I cannot get a 401 if I supply only one of them. (I have tried calling Challenge and then setting the Status to 401 in the JWT's `OnChallenge` event, I have tried setting it in a custom attribute and I have setting it in a custom middleware. No matter where I set it to 401, I always get 200 sent back out.) – Vaccano Aug 21 '20 at 00:10
  • When both JWTs are required, how exactly are you passing them in the browser? Per the RFC, you cannot pass multiple bearer tokens in the Auth header, so are you using your own custom header (X-*) to pass the tokens to your server? If so, then of course the standard .Net bearer token setup is not going to work. – Bryan Lewis Aug 21 '20 at 22:02