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"
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.