我使用带有ASP.NET核心身份的IdentityServer4的ROPC流程,我需要将用户名和密码发送到/ connect / token端点以获取access_token。
如何配置IdentityServer4接受用户名或电子邮件,以及/ connect / token请求中的密码?
PS:asp.net核心:2.0.2 IdentityServer4:2.0.2
答案 0 :(得分:3)
找到了这个解决方案:
将文件IdentityServer4.AspNetIdentity / src / IdentityServer4.AspNetIdentity / ResourceOwnerPasswordValidator.cs复制到您的项目中2)修复ValidateAsync方法以查找具有电子邮件的用户
.AddAspNetIdentity<AppUser>()
.AddResourceOwnerValidator<Services.ResourceOwnerPasswordValidator<AppUser>>();
3)将验证器添加到IS4:
$(".datepicker").datepicker().keydown(function (event) {
if(event.which === $.ui.keyCode.ENTER)
{
event.preventDefault();
console.log("enter key pressed " + $(this).val());
return false;
}
});
4)利润!
答案 1 :(得分:0)
您需要通过创建实现IResourceOwnerPasswordValidator接口的Custom PasswordValidator类来覆盖ValidateAsync,如下所示。
public class OwnerPasswordValidatorService : IResourceOwnerPasswordValidator
{
public UserManager<ApplicationUser> _userManager { get; }
public OwnerPasswordValidatorService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
var user = await _userManager.FindByNameAsync(context.UserName);
if (user == null)
{
user = await _userManager.FindByEmailAsync(context.UserName);
if (user == null)
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Username or password is incorrect");
return;
}
}
var passwordValid = await _userManager.CheckPasswordAsync(user, context.Password);
if (!passwordValid)
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Username or password is incorrect");
return;
}
context.Result = new GrantValidationResult(subject: context.UserName, authenticationMethod: "custom");
}
}
然后为您的自定义类配置依赖项,如下所示。
services.AddIdentityServer()
.AddDeveloperSigningCredential()
...
.AddAspNetIdentity<ApplicationUser>()
.AddResourceOwnerValidator<OwnerPasswordValidatorService>() //here
.AddProfileService<ProfileService>();
如果仍然无法使它工作,请告诉我。我很乐意提供帮助。