- A+
所属分类:IdentityServer4
一.前言
OAuth 2.0 资源所有者密码模式允许客户端向令牌服务发送用户名和密码,并获取代表该用户的访问令牌。
除了通过无法浏览器进行交互的应用程序之外,通常建议不要使用资源所有者密码模式。 一般来说,当您要对用户进行身份验证并请求访问令牌时,使用其中一个交互式 OpenID Connect 流程通常要好得多。
在这里使用这种模式是为了学习如何快速在 IdentityServer 中使用它。
二.添加用户
TestUser
类代表测试用户及其身份信息单元(Claim)。 让我们通过在 config
类中添加以下代码来创建几个用户。首先添加以下语句 到Config.cs文件中:
- using IdentityServer4.Test;
- public static List<TestUser> GetUsers()
- {
- return new List<TestUser>
- {
- new TestUser
- {
- SubjectId = "1",
- Username = "alice",
- Password = "password"
- },
- new TestUser
- {
- SubjectId = "2",
- Username = "bob",
- Password = "password"
- }
- };
- }
然后将测试用户注册到 IdentityServer:
- public void ConfigureServices(IServiceCollection services)
- {
- // configure identity server with in-memory stores, keys, clients and scopes
- services.AddIdentityServer()
- .AddInMemoryApiResources(Config.GetApiResources())
- .AddInMemoryClients(Config.GetClients())
- .AddTestUsers(Config.GetUsers());
- }
AddTestUsers方法帮我们做了以下几件事:
三.为资源所有者密码授权添加一个客户端定义
- 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" }
- }
- };
- }
四.使用密码授权请求一个令牌
通过如下代码获取Token
- // request token
- var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
- {
- Address = disco.TokenEndpoint,
- ClientId = "ro.client",
- ClientSecret = "secret",
- UserName = "alice",
- Password = "password",
- Scope = "api1"
- });
- if (tokenResponse.IsError)
- {
- Console.WriteLine(tokenResponse.Error);
- return;
- }
- Console.WriteLine(tokenResponse.Json);