根据凭据自定义用户数据库验证 - IResourceOwnerPasswordValidator

Validating Against credentials Custom Users DB - IResourceOwnerPasswordValidator

我正在使用 Identity Server 4 并实现了以下两个接口:

IResourceOwnerPasswordValidator:用于根据我的自定义数据库验证用户凭据

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
    }

然后在启动 class 中的服务中添加必要的接口和依赖项。我还通过注入具有以下实现的登录服务修改了帐户控制器:

   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的Login Action,然后是我的登录服务。验证用户凭据后,将显示同意页面,这会触发 ProfileService GetProfileDataAsync 方法。

但是,从未调用过 ResourceOwnerPasswordValidator。我是否以正确的方式实现了 LoginService,或者我应该替换由 IResourceOwnerPasswordValidation 注入的 IUserRepository,然后调用登录服务 ValidateCredentails 中的“ValidateAsync”方法?

如果是这样的话,将它传递给 LoginService 有什么好处,因为我已经用这种方式验证了用户?

根据docs

If you want to use the OAuth 2.0 resource owner password credential grant (aka password), you need to implement and register the IResourceOwnerPasswordValidator interface:

由于您不使用密码授予,预期的行为是不调用 ResourceOwnerPasswordValidator。对于您的情况,您不需要 ResourceOwnerPasswordValidator 实施。

我运行陷入同样的​​问题。解决方案是按照您所做的那样做,但需要修改 Startup.cs 才能看到它。

// Adds IdentityServer
services.AddIdentityServer()
    .AddResourceOwnerValidator<**PasswordAuthentication**>()

注意:确保您没有将它添加到 AddIdentity 中,后者也具有相同的 .AddResourceOwnerValidator 功能。我花了一段时间。希望这对某人有帮助。