always return 401 when I use jwt token.

mc 3,701 Reputation points
2023-05-23T04:25:12.24+00:00

I use cookie authentication for default and add a JwtBearerAuthentication.

When I get api using the token it always return 401.

.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    }

[Authorize(AuthenticationSchemes ="Bearer")]

it return 401

in headers I add {'Authentication':'Bearer {token}'}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,195 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jerry Fu - MSFT 561 Reputation points Microsoft Vendor
    2023-05-23T07:00:58.0133333+00:00

    Hi , below is a small working sample for you to test.

    Create a new asp.net core webapi project firstly. Install nuget packagemicrosoft.aspnetcore.authentication.jwtbearer

    Add a new TestController.cs

    
        [ApiController]
        public class TestController : ControllerBase
        {
            [HttpGet("GetToken")]    
            public string CreateAccessToken()
            {
                var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, "Tom"),
                        new Claim(ClaimTypes.Email, "Tom@gmail.com")
                };
    
                var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("CJKFOGk-9E0aI8Gv09mD-8utzSyLQx_yrJKi1fXc6Y7CeYszLzcmMA2C0_Ej3K7BQdsCW9zoqW3a-5L1ZNRytFC0BeA6dZLsCjoTrFoI9guwvEmJ0gbN9yHQ0fDYbkwGUyJbP6eNEzKbWHMarSx7RWGKaGsxy0qguEMSO3OUWU8"));
                var jwtInfo = new JwtSecurityToken(                  
                        issuer: "localhost",
                        audience: "audience1",
                        claims: claims,
                        expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(4)),
                        signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                        );
                var Token = new JwtSecurityTokenHandler().WriteToken(jwtInfo);
                return Token;
            }
    
            [HttpGet("api")]
            [Authorize(AuthenticationSchemes = "Bearer")]
            public string Test()
            {
                return "You have pass the bearer";
            }
        }
    

    The first method is to generate token, the second method is for bearer authentication test.

    Add the following code to program.cs, no other change is needed.

    
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                         .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                         {
                             //options.Authority = "localhost";
    
                             options.TokenValidationParameters = new TokenValidationParameters
                             {          
                                 ValidIssuer="localhost",
                                 ValidateAudience = false,
                                 IssuerSigningKey= new SymmetricSecurityKey(Encoding.ASCII.GetBytes("CJKFOGk-9E0aI8Gv09mD-8utzSyLQx_yrJKi1fXc6Y7CeYszLzcmMA2C0_Ej3K7BQdsCW9zoqW3a-5L1ZNRytFC0BeA6dZLsCjoTrFoI9guwvEmJ0gbN9yHQ0fDYbkwGUyJbP6eNEzKbWHMarSx7RWGKaGsxy0qguEMSO3OUWU8"))
                         };
                         });
    

    Then run the project. First visit "localhost:port/gettoken" to get the token value(better use browser). Second, if you visit "localhost:port/api" without header, it will return 401. And if you use postman like below, it will return "You have pass the bearer"

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments