IdentityServer Resource Owner Password

Resource Owner Password 模式需要自己实现用户名密码的校验

新增ResourceOwnerPasswordValidator实现IResourceOwnerPasswordValidator接口

public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public ResourceOwnerPasswordValidator(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var result = await _signInManager.PasswordSignInAsync(context.UserName, context.Password, false, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                context.Result = new GrantValidationResult(
                                    subject: context.UserName,
                                    authenticationMethod: "custom");
            }
            else
            {
                context.Result = new GrantValidationResult(
                                    TokenRequestErrors.InvalidGrant,
                                    "invalid custom credential");
            }
        }
    }

在Startup中注册

services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();

创建Client

public static IEnumerable<Client> GetClients()
{
    return new List<Client>
    {
        // other clients omitted...

        // resource owner password grant client
        new Client
        {
            ClientId = "ro.client",
            AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

            ClientSecrets =
            {
                new Secret("secret".Sha256())
            },
            AllowedScopes = { "api1" }
        }
    };
}

程序中使用DiscoveryClient调用

var disco = await DiscoveryClient.GetAsync("http://localhost");
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }
            var tokenClient = new TokenClient(disco.TokenEndpoint, "ro.client", "secret");
            var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync("email", "password", "api1");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");

使用postman调用

IdentityServer Resource Owner Password

调用API

IdentityServer Resource Owner Password

上一篇:Tensorflow gpu版安装教程


下一篇:springmvc4.0配置ajax请求json格式数据