1

我使用的Identity Server 4和實施了以下兩個接口:驗證反對憑據自定義用戶DB - IResourceOwnerPasswordValidator

IResourceOwnerPasswordValidator:針對我自定義的驗證用戶憑據DB

public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator 
{ 
    private IUserRepository _userRepository; 

    public ResourceOwnerPasswordValidator(IUserRepository userRepository) 
    { 
     this._userRepository = userRepository; 
    } 

    public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) 
    { 
     var isAuthenticated = _userRepository.ValidatePassword(context.UserName, context.Password); 

     //code is omitted for simplicity     
    } 
} 

的目的IProfileService:用於獲取必要的聲明

public class ProfileService : IdentityServer4.Services.IProfileService 
{ 
    public IUserRepository _userRepository; 
    public ProfileService(IUserRepository userRepository) 
    { 
     _userRepository = userRepository; 
    } 
    public Task GetProfileDataAsync(ProfileDataRequestContext context) 
    { 
     //code is ommitted 
    } 

然後在Startup類的服務中添加必要的接口和依賴項。通過調用

public class LoginService 
{ 
    private readonly IUserRepository _userRepository; 
    public LoginService(IUserRepository userRepository) 
    { 
     _userRepository = userRepository; 
    } 
    public bool ValidateCredentials(string username, string password) 
    { 
     return _userRepository.ValidatePassword(username, password); 
    } 

的的AccountController「登錄」行動驗證的憑據:我也通過注射它具有以下實現的登錄服務修改賬戶控制器

if (_loginService.ValidateCredentials(model.Username, model.Password)) 
     { 
      var user = _loginService.FindByUsername(model.Username); 
      await HttpContext.Authentication.SignInAsync(user.Subject, user.Username); 
      //other code is omitted 

在調試該項目AccountContoller的登錄動作被調用,然後是我的登錄服務。驗證用戶憑證後,會顯示許可頁面,該頁面將觸發ProfileService GetProfileDataAsync方法。

但是,ResourceOwnerPasswordValidator從未被調用過。我以正確的方式實現LoginService,還是應該替換由IResourceOwnerPasswordValidation注入的IUserRepository,然後在Login Service ValidateCredentails中調用「ValidateAsync」方法?

如果是這樣的話,那麼將它傳遞給LoginService有什麼好處,因爲我已經以這種方式驗證了用戶?

回答

3

根據docs

如果要使用OAuth 2.0資源所有者密碼憑據 補助(又名密碼),您需要實現並註冊 IResourceOwnerPasswordValidator接口:

既然你不使用密碼授權,預期的行爲是不要撥打ResourceOwnerPasswordValidator。對於你的情況,你不需要執行ResourceOwnerPasswordValidator

1

我遇到了同樣的問題。解決方案就像你所做的一樣,但是之後需要修改Startup.cs來查看它。

//添加IdentityServer services.AddIdentityServer() .AddResourceOwnerValidator < 的PasswordAuthentication>()

注意:確保你不將它添加到 「AddIdentity」,這也有同樣的.AddResourceOwnerValidator功能。我花了一段時間。希望這可以幫助某人。