如何在使用PasswordHash和SecurityStamp的现有数据库中检查用户名和密码是否有效?

时间:2017-08-09 17:30:46

标签: authentication asp.net-core asp.net-identity jwt password-hash

我是 Asp.Net Core 的新手。我已经实现了基于JWT承载令牌的身份验证和授权。令牌已成功生成,但在现有数据库中, 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自动处理)来做同样的事情

由于

1 个答案:

答案 0 :(得分:1)

Identity Core有PasswordHasher Class可以利用。举个例子,你可以这样做:

//Initialize it
var _passwordHasher = new PasswordHasher<ApplicationUser>();

找到您要验证的用户:

var user = await _userManager.FindByNameAsync(request.Username);

然后,您可以验证用户:

if (user == null || _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, request.Password) != PasswordVerificationResult.Success)            
{
return BadRequest();
}

如果通过此部分,您可以生成令牌:

var token = await GetJwtSecurityToken(user);

GetJwtSecurityToken()只是我自己的带有令牌生成令牌的功能,但我知道你已经完成了它。

我不明白为什么SO没有格式化我的代码。