0

I am making a stand alone API for a website I am building. The website gets a JWT token/refresh token from an authentication server and calls this API with the token in its authorization header using

_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 

In the API Startup I have the code (I didn't write this part so I'm not sure if its necessary)

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.SaveToken = true;
    options.TokenValidationParameters = tokenValidation.GetTokenValidationParameters();
});

the tokenValidation is a Service which implements ISecureDataFormat<AuthenticationTicket>.

So with that background here is my question. When the Website makes a HTTP request to the API, do I still use the Authorize attribute? My understanding is that a token must be sent with every request so I'm not sure how the website could stay authenticated with the API. The alternative would be to make every endpoint "public" but validate the token at each one. I hope this makes sense.

Edit:

I should also ask. Would this be an appropriate place to use a custom [Authorize] header or policy as discussed in this thread?

Edit 2:

I'm dumb. This code does work. By including the token validation parameters in the authorization any endpoint with the [authorize] header will automatically check for a token and validate it. So this code is working and I had a small error elsewhere in my code (wrong name to controller). Feel free to ignore this question.

arc-menace
  • 435
  • 6
  • 19

1 Answers1

0

By default, all endpoints will be accessible unless decorated with [Authorize]. Arguably a better approach for a secure API is to set a global default requiring all requests be authorized, then specifically exempt any endpoints that should allow anonymous access.

From documentation:

services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});
Noah Stahl
  • 6,905
  • 5
  • 25
  • 36