问题描述: 在ASP.NET Core Web API中,使用JWT承载令牌授权时,授权不起作用。
解决方法: 以下是一些可能的解决方法,根据具体情况选择适合的方法:
public void ConfigureServices(IServiceCollection services)
{
// ...
// 配置认证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your_issuer",
ValidAudience = "your_audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
};
});
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
app.UseAuthorization();
// ...
}
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class MyController : ControllerBase
{
// ...
}
public IActionResult Login()
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("your_secret_key");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "your_username"),
new Claim(ClaimTypes.Role, "your_role")
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new { Token = tokenString });
}
[HttpGet]
[Authorize]
public IActionResult Get()
{
// ...
}
请注意,上述代码示例中的密钥、发行者、听众等参数应根据自己的情况进行配置。
希望这些解决方法能帮助您解决ASP.NET Core Web API中JWT承载令牌授权不起作用的问题。