我是Asp.Net Core。我已实施基于JWT承载令牌的身份验证和授权。令牌生成成功,但在现有数据库中,AspNetUser表具有加密格式的密码,其密码为PasswordHash和SecurityStamp列。那么,我如何从数据库中检查用户名和密码?如何使用PasswordHash和SecurityStamp检查用户名和密码是否有效?
请找到了部分启动类的下面的代码生成令牌:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
ConfigureAuth(app);
app.UseMvc();
}
和
public partial class Startup
{
// The secret key every token will be signed with.
// Keep this safe on the server!
private static readonly string secretKey = "mysupersecret_secretkey!123";
private void ConfigureAuth(IApplicationBuilder app)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
app.UseSimpleTokenProvider(new TokenProviderOptions
{
Path = "/api/token",
Audience = "ExampleAudience",
Issuer = "ExampleIssuer",
SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
IdentityResolver = GetIdentity
});
var tokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = "ExampleIssuer",
// Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = "ExampleAudience",
// Validate the token expiry
ValidateLifetime = true,
// If you want to allow a certain amount of clock drift, set that here:
ClockSkew = TimeSpan.Zero
};
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters
});
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
AuthenticationScheme = "Cookie",
CookieName = "access_token",
TicketDataFormat = new CustomJwtDataFormat(
SecurityAlgorithms.HmacSha256,
tokenValidationParameters)
});
}
private Task<ClaimsIdentity> GetIdentity(string username, string password)
{
// Here i want to match username and password with passwordHash and SecurityStamp
if (username == "TEST" && password == "TEST123")
{
return Task.FromResult(new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { }));
}
// Credentials are invalid, or account doesn't exist
return Task.FromResult<ClaimsIdentity>(null);
}
}
在上面的代码中,我检查与硬编码值的用户名和密码,但我需要通过使用现有的数据库与AspNetUser表(由MVC5自动处理)做同样的事情
谢谢
jwt与它有什么关系?似乎与这个问题无关。 –
JWT用于在验证电子邮件和密码后生成令牌以返回 –
但是,生成令牌没有问题,为什么要提及它?无论如何,如果您添加信息,例如您使用什么(包)来实现安全性,它会有所帮助?你有没有实现一个用户管理器?你能展示一些(相关的)代码吗? –