asp.net-core - .net Core 3 Web API JWT 未经授权
问题描述
我是身份验证领域的初学者,我正在尝试实现一个简单的示例来保护我的 api。
在我的登录操作中,我生成了一个 JWT,例如:
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ThIsIsAKeyT03ncrypt!4lw4ysUs3AStr0ng1"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "https://localhost:44392/",
audience: "https://localhost:44392/",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
我的控制器标记如下:
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class WeatherForecastController : ControllerBase
{
StartUp 类处理身份验证,如:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
和:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = "https://localhost:44392/",
ValidAudience = "https://localhost:44392/",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ThIsIsAKeyT03ncrypt!4lw4ysUs3AStr0ng1")),
ValidateLifetime = true
};
});
问题是,虽然我使用相同的对称密钥、颁发者和受众,但通过邮递员测试时,结果始终是状态 401。
是否有我缺少的设置/选项?欢迎任何帮助
解决方案
通过添加解决的问题
services.AddAuthentication(cfg =>
{
cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
在 StartUp 类中。
推荐阅读
- javascript - 如何将输入复选框中的值传递给jquery中的URL参数
- r - 如何对 47 个 nlevel 进行分类?
- python - 根据 API 中的标签返回下一页结果
- typescript - 我需要通过数据表获取一个对象数组,在cypress中使用cucumber
- git - 有人可以帮我将代码推送到我的 github 存储库吗?
- firebase - 从 AsyncSnapshot 对 Firebase 数据进行排序
> 带有 Dart .sort() 函数 - python - Pytorch 张量 MNIST 图像绘图
- javascript - 在 ReactJS 中解构 props
- google-sheets - 范围中的数据验证下拉列表,而不是仅在不使用第二个计算表的情况下有条件地显示值
- javascript - 如何在 HTML 中使用 JS 动态设置值单选按钮