Как проверить, что имя пользователя и пароль действительны или нет в существующей базе данных с PasswordHash и SecurityStamp?

Я новичок в Asp.Net Core. Я реализовал аутентификацию и авторизацию на основе маркеров JWT Bearer. Токен создан успешно, но в существующей базе данных таблица AspNetUser имеет пароль в зашифрованном виде со столбцами PasswordHash и SecurityStamp. Итак, как я могу проверить имя пользователя и пароль из базы данных?

Ниже приведен код частичного класса Startup для генерации токена:

    // 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 ответ

Identity Core имеет класс PasswordHasher, который вы можете использовать. Как пример, вы можете сделать, как показано ниже:

//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 не форматирует мой код.

Другие вопросы по тегам