网站建设保密,平面设计和电商设计,高州女网红遇害案犯罪嫌疑人被抓获,旅游做攻略网站继续介绍IdentityServer4,我们上篇介绍了IdentityServer4实现OAuth2.0的授权方式之一的客户端凭证#xff0c;接下来我们继续介绍OAuth2.0的另外一种授权方式密码式#xff0c;Resource Owner Password Credentials。post请求token?grant_typepasswordusernameUSERNAME… 继续介绍IdentityServer4,我们上篇介绍了IdentityServer4实现OAuth2.0的授权方式之一的客户端凭证接下来我们继续介绍OAuth2.0的另外一种授权方式密码式Resource Owner Password Credentials。post请求token?grant_typepasswordusernameUSERNAMEpasswordPASSWORDclient_idCLIENT_IDclient_secretsecret从上面url的querystring参数就可以看出来这里主要就是需要提供用户的用户名和密码这个在传统的项目还是比较常见web后台管理系统C/S客户端1.更新IdentityServer由于上篇【One by One系列】IdentityServer4二使用客户端凭证(Client Credentials)保护API资源已经创建的IdentityServer项目我们只需要IdentityServer4中注册用户和添加新的客户端。1.1 注册用户客户端凭证是没有用户参与的但是密码式不同需要用户输入用户名和密码自然就需要用户数据。当然这块内容就属于OpenID Connect了因为这跟身份认证相关。我们在Config.cs里面增加用户数据public static ListTestUser TestUsers new ListTestUser{new TestUser(){SubjectId1,Usernameadmin,Passwordadmin123456!,Claims{ new Claim(JwtClaimTypes.Name,RandyField),new Claim(JwtClaimTypes.GivenName,Randy),new Claim(JwtClaimTypes.FamilyName,Field),new Claim(JwtClaimTypes.Email,xxxqq.com),new Claim(JwtClaimTypes.EmailVerified,true,ClaimValueTypes.Boolean),new Claim(JwtClaimTypes.WebSite,http://www.randyfield.cn),new Claim(JwtClaimTypes.FamilyName,Randy),new Claim(JwtClaimTypes.Address,$四川省成都市高新区)} }};
1.2 注册身份资源代码如下public static IEnumerableIdentityResource IdentityResources new IdentityResource[]{//必须要添加否则报无效的scope错误new IdentityResources.OpenId(),new IdentityResources.Profile()};
1.3 注册新客户端代码如下 public static IEnumerableClient Clients new Client[]{new Client{ClientId client app,// no interactive user, use the clientid/secret for authenticationAllowedGrantTypes GrantTypes.ClientCredentials,// secret for authenticationClientSecrets {new Secret(secret-123456.Sha256())},// scopes that client has access toAllowedScopes { api1 }},//Resource Owner Password Credentials Clientnew Client{ClientIdclient pwd,AllowedGrantTypesGrantTypes.ResourceOwnerPassword,ClientSecrets{new Secret(secret-654321.Sha256())},AllowedScopes{ api1,IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile }},};
这里客户端AllowedScopes除了api资源还额外指定了用户Identity资源2.创建客户端这里我们依然使用上篇的中的客户端控制台程序只是增加代码模拟密码式授权2.1 编码-请求Idisconvery endpoint略与上篇相同2.2 编码-请求access token // request tokenvar tokenResponse1 await client.RequestPasswordTokenAsync(new PasswordTokenRequest{Address disco.TokenEndpoint,ClientId client pwd,//ClientId client,ClientSecret secret-654321,Scope api1 openid profile,UserName admin,Password admin123456!});if (tokenResponse1.IsError){Console.WriteLine(tokenResponse1.Error);return;}
RequestClientCredentialsTokenAsync更换为RequestPasswordTokenAsync请求参数ClientCredentialsTokenRequest更换为PasswordTokenRequest其中的用户名和密码就是在IdentityServer注册的用户ClientId与ClientSecret就不赘述了Scope指明了api资源和Identity资源3.测试启动IdentityServercd .\IdentityServer\
dotnet run
启动webapicd .\webapi\
dotnet run
用vs启动client3.1 获取access-token我们通过http://jwt.calebb.net/解析3.2 调用api3.3 获取身份信息调用userinfo端点,获取身份信息长按二维码关注点外卖先领券