【发布时间】:2018-01-17 17:24:07
【问题描述】:
我是 Asp.Net Core 的新手。我已经实现了 基于 JWT Bearer Token 的身份验证和授权。令牌生成成功,但在现有数据库中,AspNetUser 表有加密格式的密码,带有 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 生成 Token 验证邮箱和密码后返回
-
但是生成token没有问题,为什么要提呢?无论如何,如果您添加信息会有所帮助,例如您使用什么(包)来实现安全性?你实现了用户管理器吗?你能展示一些(相关的)代码吗?
-
@RuardvanElburg 我已经更新了问题,请检查
-
我没有实现用户管理器
标签: authentication asp.net-core asp.net-identity jwt password-hash