【问题标题】:How to check username and password is valid or not in existing database with PasswordHash and SecurityStamp?如何使用 PasswordHash 和 SecurityStamp 在现有数据库中检查用户名和密码是否有效?
【发布时间】:2018-01-17 17:24:07
【问题描述】:

我是 Asp.Net Core 的新手。我已经实现了 基于 JWT Bearer Token 的身份验证和授权。令牌生成成功,但在现有数据库中,AspNetUser 表有加密格式的密码,带有 PasswordHashSecurityStamp 列。那么,如何从数据库中查看用户名和密码呢?

请在下面找到生成令牌的部分启动类代码:

    // 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


【解决方案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();
}

如果通过了这一部分,就可以生成token了:

var token = await GetJwtSecurityToken(user);

GetJwtSecurityToken() 只是我自己的带有令牌生成令牌的函数,但我知道您已经完成了。

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

【讨论】:

  • 这行显示对象引用未设置错误{System.Data.SqlClient.SqlException: Invalid column name 'NormalizedUserName'.. 我认为这与用户管理器实现有关
猜你喜欢
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 2022-12-25
  • 2018-03-30
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多