创建了一个身份验证Api以处理多个应用程序的身份验证。这是基本的身份验证。用户名和密码。没有与Google等的OAuth。使用凭据调用api,并以AthenticationResult进行响应。除了AuthenticationResult.Success之外,它都可以正常工作。据我了解,我无法序列化ClaimsPrincipal。在我阅读时,似乎可以将其转换为令牌。它是否正确? AuthenticationResult.Failed序列化无问题。什么是最好的解决方案。我会继续看的。
谢谢阅读
答案 0 :(得分:0)
是的,您需要完成以下步骤:
authorize
标头的一部分。有一个很棒的ASP.NET Core 2.2 JWT Authentication Tutorial,您应该看看。
涉及到太多的代码,无法完整地发布所有代码,但是这里有一些关键代码片段(对某些代码进行了稍微的修改,以使教程更加清晰明了):
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
// 'user' is the model for the authenticated user
// also note that you can include many claims here
// but keep in mind that if the token causes the
// request headers to be too large, some servers
// such as IIS may reject the request.
new Claim(ClaimTypes.Name, user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
不要忘记将应用程序配置为在Startup.cs Configure
方法中实际使用身份验证:
app.UseAuthentication();