即使在 asp.net core 5.0 中提供了不记名令牌,也会返回 401 [关闭]
Posted
技术标签:
【中文标题】即使在 asp.net core 5.0 中提供了不记名令牌,也会返回 401 [关闭]【英文标题】:401 is returned even when bearer token is provied in asp.net core 5.0 [closed] 【发布时间】:2021-04-21 09:01:11 【问题描述】:所以我正在尝试为我的 web api 应用程序设置身份验证。现在我只是在乱搞并试图让我的授权端点工作承载令牌,但即使使用令牌我仍然得到 401。我想我已经尝试了所有的方法,但它仍然拒绝工作。
目前我有这个
返回令牌的代码
public async Task<UserResponseWithToken> Authenticate(string email, string password)
if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
return null;
var user = await _userRepository.GetByEmailAsync(email);
if (user == null)
return null;
if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
return null;
var userResponse = _mapper.Map<UserResponseWithToken>(user);
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authenticationConfiguration.Secret));
var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);
Console.WriteLine(_authenticationConfiguration.Secret);
var token = new JwtSecurityToken(
issuer: _authenticationConfiguration.Issuer,
audience: _authenticationConfiguration.Audience,
expires: DateTime.Now.AddHours(1)
);
userResponse.Token = new JwtSecurityTokenHandler().WriteToken(token);
return userResponse;
授权端点
[HttpGet("alarms")]
[Authorize(AuthenticationSchemes=JwtBearerDefaults.AuthenticationScheme)]
在启动中配置方法
databaseContext.Database.Migrate();
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseRouting();
配置服务
services.Configure<AuthenticationConfiguration>(Configuration.GetSection("Authentication"));
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Authentication:Secret"]));
var audience = Configuration["Authentication:Audience"];
var issuer = Configuration["Authentication:Issuer"];
services.AddAuthentication(x =>
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
)
.AddJwtBearer(options =>
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
//what to validate
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
//validation data
ValidIssuer = issuer,
ValidAudience = audience,
IssuerSigningKey = symmetricSecurityKey
;
);
services.AddAuthorization(options =>
var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(
JwtBearerDefaults.AuthenticationScheme);
defaultAuthorizationPolicyBuilder =
defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
);
【问题讨论】:
您的var token = new JwtSecurityToken
行没有意义。您需要一个 SecurityTokenDescriptor
实例来正确识别正在登录的用户(JWT 需要一个主题)。
【参考方案1】:
您的创建令牌没有签名凭据,添加它们:
var token = new JwtSecurityToken(
signingCredentials:signingCredentials,
issuer: _authenticationConfiguration.Issuer,
audience: _authenticationConfiguration.Audience,
expires: DateTime.Now.AddHours(1)
);
【讨论】:
好吧,我真是太傻了。不过谢谢。以上是关于即使在 asp.net core 5.0 中提供了不记名令牌,也会返回 401 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
如何确定在 C# ASP.NET CORE MVC 5.0 中选择了哪个单选按钮
如何按照存储库模式在 Asp.Net Core 5.0 项目上实现 .Net Core Identity?
ASP.NET Core 5.0 WebAPI 中的多种身份验证方案
EF Core 5.0 - 更新 ASP.NET Core Web API 中的多对多实体