1

我是Asp.Net Core。我已实施基于JWT承载令牌的身份验证和授权。令牌生成成功,但在现有数据库中,AspNetUser表具有加密格式的密码,其密码为PasswordHashSecurityStamp列。那么,我如何从数据库中检查用户名和密码?如何使用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自动处理)做同样的事情

谢谢

+0

jwt与它有什么关系?似乎与这个问题无关。 –

+0

JWT用于在验证电子邮件和密码后生成令牌以返回 –

+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()只是我自己的函数与令牌生成令牌,但我知道你已经完成了你的目的。

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

+0

它显示对象引用未在此行上设置错误'{系统。 Data.SqlClient.SqlException:无效的列名'NormalizedUserName'..我认为这与usermanager实现有关 –

相关问题