Matthew Matthew - 3 months ago 521
ASP.NET (C#) Question

Identity server 4 - resource owner password validator

IdentityServer4 throws me an exception when I want to use ResourceOwner GrantType.

How can I implement IResourceOwnerPasswordValidator in ASP.NET Core using ASP.NET Core default user database?

Answer

Check out official samples repository.

Here is my own implementation of IResourceOwnerPasswordValidator:

public class AspNetIdentityResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
    private readonly UserManager<ApplicationUser> _userManager;

    public AspNetIdentityResourceOwnerPasswordValidator(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<CustomGrantValidationResult> ValidateAsync(string userName, string password, ValidatedTokenRequest request)
    {
        var user = await _userManager.FindByNameAsync(userName);
        if (user != null && await _userManager.CheckPasswordAsync(user, password))
        {
            if (!await _userManager.IsEmailConfirmedAsync(user))
            {
                return new CustomGrantValidationResult("Email is not confirmed");
            }
            return new CustomGrantValidationResult(user.Id, "password");
        }


        return new CustomGrantValidationResult("Invalid username or password");
    }
}

You have to also invoke services.AddTransient<IResourceOwnerPasswordValidator, AspNetIdentityResourceOwnerPasswordValidator>(); at Startup.cs ConfigureServices() in order to use ResourceOwner GrantType.

Comments