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實現有關 –

相關問題