我正在使用 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
}
然后将必要的接口和依赖项添加到 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 有什么好处,因为我已经在以这种方式验证用户了?