'Authorazation with JWT Token - How to get Authorized Automatically

I'm having a problem getting a user to be authorized.

I'm making a web Api and in the controller where the login method is, it creates a token (JWT Token / Bearer Token), but I don't know how to put the user who logged in automatically authorized.

"Manually" and by swagger I had the following that was after login I had the token and in one button (AddSwaggerGen(options => { options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme) put the word bearer + ' ' + token and I was already authorized but at the moment I'm trying to replace the swagger with normal html + js. (I call methods by fetch) and when pressing the login button he has to do the authentication and authorization soon.

I send the code I have from my project:

[HttpPost("login")]
        public async Task<ActionResult<string>> Login(LoginModel request)
        {
          //Here i have code who checks if is a valid user

            string token = CreateToken(user); //creates a token giving roles, keys, creds, 
                                                put in a var token and do a jwtsecurity

            var refreshToken = GenerateRefreshToken(); //this is useful for refreshTokens 
            
            //check if string token is valid
            if (!ValidateToken(token))
            {
                return BadRequest("Check if is a valid token!");
            }
            
            //this method is just to put the refresh token with the user
            SetRefreshToken(refreshToken);

            //here i just have code who updates the database refresh token

            //THE REAL PROBLEM (this is not working)
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new 
                AuthenticationHeaderValue("Bearer", token);
            }
            
            // Also I try do just this line but it gives me a error in the httpClient not 
            being recognize
            httpClient.DefaultRequestHeaders.Authorization = new 
            AuthenticationHeaderValue("Bearer", token);

            return Ok(token);
        }

Does anyone know how to replace the code I have to correctly do the automatic authorization?

Any common sense answer is always welcome and sorry if my english is not the best



Solution 1:[1]

I think the problem you are having is that you are confusing the concepts of authentication and authorization, as explained by the ASP.NET Core documentation here:

Authentication is the process of determining a user's identity. Authorization is the process of determining whether a user has access to a resource.

So that means both processes can't be done together.

As you can see on this JWT Auth flow, you have to first authenticate the user, so your API can issue a JWT for this user and send it back to your API's consumer/client application.

Your consumer/client application is now responsible to store the issued JWT token (e.g. local storage for a web app) and attach it to the HTTP Authorization header of every request that it needs to be authorized for the user, your API is only responsible to verify the JWT token.

To do so with the [Authorize] attribute you have to add the following configuration on your startup file.

// Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // JWT validation configuration
     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
     {
          var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(symmetricKeyValue));

          options.TokenValidationParameters = new TokenValidationParameters
          {
                IssuerSigningKey = symmetricKey,
                ClockSkew = TimeSpan.Zero,
                ValidIssuer = issuerValue,
                ValidAudience = audienceValue,
                ValidateIssuerSigningKey = true,
                ValidateLifetime = true,
                ValidateIssuer = true,
                ValidateAudience = true,
          };
      });

      // Enables [Authorize] attribute
      services.AddAuthorization();

      // API controllers or your endpoint configuration
      services.AddControllers();
}

Note: All the values on services.AddAuthentication() can be configured accordingly to your needs.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1