创建客户端

在创建了 IdentityServer4 服务器之后,我们可以准备从获取一个访问令牌开始。

1. 客户端凭证式验证流

在 OpenID Connect 中,最为简单的验证方式为客户端凭借方式了。我们从这种方式开始。OpenID Connect 是 OAuth 的扩展,我们找一段阮一峰的博客来进行说明。

第四种方式:凭证式

最后一种方式是凭证式(client credentials),适用于没有前端的命令行应用,即在命令行下请求令牌。

第一步,A 应用在命令行向 B 发出请求。

https://oauth.b.com/token?
grant_type=client_credentials&
client_id=CLIENT_ID&
client_secret=CLIENT_SECRET

上面 URL 中,grant_type参数等于client_credentials表示采用凭证式,client_idclient_secret用来让 B 确认 A 的身份。

第二步,B 网站验证通过以后,直接返回令牌。

这种方式给出的令牌,是针对第三方应用的,而不是针对用户的,即有可能多个用户共享同一个令牌。

原文地址:http://www.ruanyifeng.com/blog/2019/04/oauth-grant-types.html

2. 服务器端实现

实际的服务端点在上一篇中,通过访问端点 http://localhost:5000/.well-known/openid-configuration 就可以得到,从响应的结果中可以找到如下的一行:

 "token_endpoint": "http://localhost:5000/connect/token",

而客户端的标示和密钥则需要我们在服务器端提供。

将上一个项目中的 Config.cs 文件替换为如下内容,代码中硬编码了客户端的标识为 client ,密钥为 secret

// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Models;
using System.Collections.Generic; namespace IdentityServer
{
public static class Config
{
public static IEnumerable<IdentityResource> Ids =>
new IdentityResource[]
{
new IdentityResources.OpenId()
}; // scopes define the API resources in your system
public static IEnumerable<ApiResource> Apis =>
new List<ApiResource>
{
new ApiResource("api1", "My API")
}; // clients want to access resources (aka scopes)
public static IEnumerable<Client> Clients =>
new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
};
}
}

在这里通过 Apis 这个委托提供了 API 资源,通过 Clients 这个委托提供了客户端的凭据。

在启动应用之后,我们可以访问服务器来获取令牌。

3. 获取访问令牌

这里,我们使用 Postman 来完成。

将请求的发送方式修改为 Post

地址设置为:http://localhost:5000/connect/token

请求的 Body ,在 Body 的设置中,首先选中格式:x-www-form-urlencoded,提供如下三个参数:

KEY VALUE
grant_type client_credentials
client_id Client
client_secret Secret

点击 Send 按钮,发送请求之后,就应该可以看到如下的响应内容:

{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IklWR2VMQ3h5NFJjcWJnbmUxb1JVN3ciLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1ODU4MTQwNzMsImV4cCI6MTU4NTgxNzY3MywiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjoiYXBpMSIsImNsaWVudF9pZCI6ImNsaWVudCIsInNjb3BlIjpbImFwaTEiXX0.R5RNGRM6bVvdNIgdXnD-QK5HK-kHA5hcZ-ltn0K3kLZp9R3BGQeg5qfnQXT4sU2CqPGYIatwbZY3bysQ9krkq5BpWzSzwY7EYPybsP3gty0BUK2QXnEwxsT1boN_cM2Hw9ua4nal3IHB4XJJkMj7jo33S8NtQQyJr26_G1WqlOgvlVfUiPYQWiY9OHPgTAIqrU_4aogoxiC84lHWC5Pf6oX6jxLoAWzKkhl-NdH33gW169xdtkPXp51XpbXhxNujBo7LAVOI-_5ztouuYLShOf5bOt1bunHfeNCv1DPl2rBsfFITjkoltQXVrTSZGLEQgNH_ryBqdoTyM-jWP1HN4g",
"expires_in": 3600,
"token_type": "Bearer",
"scope": "api1"
}

4. 实现自定义的存储

这个 Config 中提供的静态属性只是为了方便进行简单的测试,在 IdentityServer4 内部,定义了验证客户端的接口 IClientStore,如下所示:

// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Models;
using System.Threading.Tasks; namespace IdentityServer4.Stores
{
/// <summary>
/// Retrieval of client configuration
/// </summary>
public interface IClientStore
{
/// <summary>
/// Finds a client by id
/// </summary>
/// <param name="clientId">The client id</param>
/// <returns>The client</returns>
Task<Client> FindClientByIdAsync(string clientId);
}
}

源码地址:https://github.com/IdentityServer/IdentityServer4/blob/master/src/Storage/src/Stores/IClientStore.cs

在 IdentityServer4 的内部,也实现了一个基于内存中集合实现的内存中客户端存储 InMemoryClientStore,代码实现如下:

// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Extensions;
using IdentityServer4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace IdentityServer4.Stores
{
/// <summary>
/// In-memory client store
/// </summary>
public class InMemoryClientStore : IClientStore
{
private readonly IEnumerable<Client> _clients; /// <summary>
/// Initializes a new instance of the <see cref="InMemoryClientStore"/> class.
/// </summary>
/// <param name="clients">The clients.</param>
public InMemoryClientStore(IEnumerable<Client> clients)
{
if (clients.HasDuplicates(m => m.ClientId))
{
throw new ArgumentException("Clients must not contain duplicate ids");
}
_clients = clients;
} /// <summary>
/// Finds a client by id
/// </summary>
/// <param name="clientId">The client id</param>
/// <returns>
/// The client
/// </returns>
public Task<Client> FindClientByIdAsync(string clientId)
{
var query =
from client in _clients
where client.ClientId == clientId
select client; return Task.FromResult(query.SingleOrDefault());
}
}
}

源码地址:https://github.com/IdentityServer/IdentityServer4/blob/master/src/IdentityServer4/src/Stores/InMemory/InMemoryClientStore.cs

你看,我们只需要传一个 Client 的可迭代对象就可以构造这样一个 InMemoryClientStore 对象实例。实际上,我们调用的 AddInMemoryClients 这个扩展方法确实就是这么做的:

/// <summary>
/// Adds the in memory clients.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="clients">The clients.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddInMemoryClients(this IIdentityServerBuilder builder, IEnumerable<Client> clients)
{
builder.Services.AddSingleton(clients); builder.AddClientStore<InMemoryClientStore>(); var existingCors = builder.Services.Where(x => x.ServiceType == typeof(ICorsPolicyService)).LastOrDefault();
if (existingCors != null &&
existingCors.ImplementationType == typeof(DefaultCorsPolicyService) &&
existingCors.Lifetime == ServiceLifetime.Transient)
{
// if our default is registered, then overwrite with the InMemoryCorsPolicyService
// otherwise don't overwrite with the InMemoryCorsPolicyService, which uses the custom one registered by the host
builder.Services.AddTransient<ICorsPolicyService, InMemoryCorsPolicyService>();
} return builder;
}

源码地址:https://github.com/IdentityServer/IdentityServer4/blob/master/src/IdentityServer4/src/Configuration/DependencyInjection/BuilderExtensions/InMemory.cs

这里使用了依赖注入完成 InMemoryClientStore 的构造注入。

好了,我们自己实现一个自定义的客户端凭据存储。比如 CustomClientStore。

在构造函数中,我们构建了内部存储客户端凭据的集合,由于实现了 IClientStore ,在实现的方法中,提供了检索客户端端的实现,其实这个方法完全从 InMemoryClientStore 复制过来的。

using IdentityServer4.Models;
using IdentityServer4.Stores;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace IdentityServer
{
public class CustomClientStore : IClientStore
{
private readonly IEnumerable<Client> _clients;
public CustomClientStore()
{
_clients = new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
};
} public Task<Client> FindClientByIdAsync(string clientId)
{
var query =
from client in _clients
where client.ClientId == clientId
select client; return Task.FromResult(query.SingleOrDefault());
}
}
}

在 .NET Core 中,服务是通过依赖注入的方式被使用的,所以,我们需要注册这个服务。回到 Startup.cs 这个文件,将 ConfigureServices() 方法替换为如下内容。

public void ConfigureServices(IServiceCollection services)
{
// uncomment, if you want to add an MVC-based UI
//services.AddControllersWithViews(); services.AddSingleton<IClientStore, CustomClientStore>(); var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis); // not recommended for production - you need to store your key material somewhere secure
builder.AddDeveloperSigningCredential();
}

主要做了两件事:

  1. 删除了原来的 .AddInMemoryClients(Config.Clients);
  2. 添加了 services.AddSingleton<IClientStore, CustomClientStore>(); 来注册服务实现

重新运行程序,并使用 Postman 访问,可以重新得到一个新的访问令牌。

控制台输出如下所示:

PS C:\temp\is4\IdentityServer> dotnet run
[02:06:36 Information]
Starting host... [02:06:37 Information] IdentityServer4.Startup
Starting IdentityServer4 version 3.1.0.0 [02:06:37 Information] IdentityServer4.Startup
You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes
, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch
to a different store implementation. [02:06:37 Information] IdentityServer4.Startup
Using the default authentication scheme idsrv for IdentityServer [02:06:37 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for authentication [02:06:37 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for sign-in [02:06:37 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for sign-out [02:06:37 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for challenge [02:06:37 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for forbid [02:06:59 Debug] IdentityServer4.Startup
Login Url: /Account/Login [02:06:59 Debug] IdentityServer4.Startup
Login Return Url Parameter: ReturnUrl [02:06:59 Debug] IdentityServer4.Startup
Logout Url: /Account/Logout [02:06:59 Debug] IdentityServer4.Startup
ConsentUrl Url: /consent [02:06:59 Debug] IdentityServer4.Startup
Consent Return Url Parameter: returnUrl [02:06:59 Debug] IdentityServer4.Startup
Error Url: /home/error [02:06:59 Debug] IdentityServer4.Startup
Error Id Parameter: errorId [02:06:59 Debug] IdentityServer4.Hosting.EndpointRouter
Request path /connect/token matched to endpoint type Token [02:06:59 Debug] IdentityServer4.Hosting.EndpointRouter
Endpoint enabled: Token, successfully created handler: IdentityServer4.Endpoints.TokenEndpoint [02:06:59 Information] IdentityServer4.Hosting.IdentityServerMiddleware
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.TokenEndpoint for /connect/token [02:06:59 Debug] IdentityServer4.Endpoints.TokenEndpoint
Start token request. [02:06:59 Debug] IdentityServer4.Validation.ClientSecretValidator
Start client validation [02:06:59 Debug] IdentityServer4.Validation.BasicAuthenticationSecretParser
Start parsing Basic Authentication secret [02:06:59 Debug] IdentityServer4.Validation.PostBodySecretParser
Start parsing for secret in post body [02:06:59 Debug] IdentityServer4.Validation.SecretParser
Parser found secret: PostBodySecretParser [02:06:59 Debug] IdentityServer4.Validation.SecretParser
Secret id found: client [02:06:59 Debug] IdentityServer4.Validation.SecretValidator
Secret validator success: HashedSharedSecretValidator [02:06:59 Debug] IdentityServer4.Validation.ClientSecretValidator
Client validation success [02:06:59 Debug] IdentityServer4.Validation.TokenRequestValidator
Start token request validation [02:06:59 Debug] IdentityServer4.Validation.TokenRequestValidator
Start client credentials token request validation [02:06:59 Debug] IdentityServer4.Validation.TokenRequestValidator
client credentials token request validation success [02:06:59 Information] IdentityServer4.Validation.TokenRequestValidator
Token request validation success, {"ClientId": "client", "ClientName": null, "GrantType": "client_credentials", "Scopes"
: "api1", "AuthorizationCode": null, "RefreshToken": null, "UserName": null, "AuthenticationContextReferenceClasses": nu
ll, "Tenant": null, "IdP": null, "Raw": {"grant_type": "client_credentials", "client_id": "client", "client_secret": "**
*REDACTED***"}, "$type": "TokenRequestValidationLog"} [02:06:59 Debug] IdentityServer4.Services.DefaultClaimsService
Getting claims for access token for client: client [02:06:59 Debug] IdentityServer4.Endpoints.TokenEndpoint
Token request success.

通过 IdentityServer4 提供的扩展方法 AddClientStore() ,还可以使用 IdentityServer4 来完成服务的注册。

            var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddClientStore<CustomClientStore>();

祝你顺利!

在 IdentityServer4 中创建客户端的更多相关文章

  1. IdentityServer4 中文文档 -15- (快速入门)添加 JavaScript 客户端

    IdentityServer4 中文文档 -15- (快速入门)添加 JavaScript 客户端 原文:http://docs.identityserver.io/en/release/quicks ...

  2. IdentityServer4 中文文档 -9- (快速入门)使用客户端凭证保护API

    IdentityServer4 中文文档 -9- (快速入门)使用客户端凭证保护API 原文:http://docs.identityserver.io/en/release/quickstarts/ ...

  3. [gRPC] 在 .NET Core 中创建 gRPC 服务端和客户端

    gRPC 官网:https://grpc.io/ 1. 创建服务端 1.1 基于 ASP.NET Core Web 应用程序模板创建 gRPC Server 项目. 1.2 编译并运行 2. 创建客户 ...

  4. 关于 IdentityServer4 中的 Jwt Token 与 Reference Token

    OpenID Connect(Core),OAuth 2.0(RFC 6749),JSON Web Token (JWT)(RFC 7519) 之间有着密不可分联系,对比了不同语言的实现,还是觉得 I ...

  5. IdentityServer4 中文文档 -16- (快速入门)使用 EntityFramework Core 存储配置数据

    IdentityServer4 中文文档 -16- (快速入门)使用 EntityFramework Core 存储配置数据 原文:http://docs.identityserver.io/en/r ...

  6. IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity

    IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity 原文:http://docs.identityserver.io/en/release ...

  7. IdentityServer4 中文文档 -12- (快速入门)添加外部认证支持

    IdentityServer4 中文文档 -12- (快速入门)添加外部认证支持 原文:http://docs.identityserver.io/en/release/quickstarts/4_e ...

  8. IdentityServer4 中文文档 -11- (快速入门)添加基于 OpenID Connect 的用户认证

    IdentityServer4 中文文档 -11- (快速入门)添加基于 OpenID Connect 的用户认证 原文:http://docs.identityserver.io/en/releas ...

  9. IdentityServer4 中文文档 -8- (快速入门)设置和概览

    IdentityServer4 中文文档 -8- (快速入门)设置和概览 原文:http://docs.identityserver.io/en/release/quickstarts/0_overv ...

  10. IdentityServer4 中文文档 -10- (快速入门)使用密码保护API

    IdentityServer4 中文文档 -10- (快速入门)使用密码保护API 原文:http://docs.identityserver.io/en/release/quickstarts/2_ ...

随机推荐

  1. Android10.0系统启动之Launcher(桌面)启动流程-[Android取经之路]

    Launcher的启动经过了三个阶段: 第一个阶段:SystemServer完成启动Launcher Activity的调用 第二个阶段:Zygote()进行Launcher进程的Fork操作 第三个 ...

  2. /proc/buddyinfo

    在应用程序设计过程中,内存是很重要的资源,而计算机主机的内存资源时有限的.一般而言我们可以申请到的内存是有限的,并不是想申请多大就有多大就可以申请多大的./proc/buddyinfo文件里,就记录着 ...

  3. 巅峰对话在线研讨 Q&A:Oracle Database 21c vs openGauss 2.0新特性解读和架构演进

    2021年11月11日,墨天轮<巅峰对话>栏目邀请到了两位数据库领域的巅峰人物:云和恩墨创始人盖国强老师,和来自清华大学计算机与技术系的李国良教授,为大家带来了在线研讨<Oracle ...

  4. Android复习(三)清单文件中的元素

    <action> 向 Intent 过滤器添加操作. <activity> 声明 Activity 组件. <activity-alias> 声明 Activity ...

  5. 在 Exchange Server 中配置特定于客户端的消息大小限制

    在 Exchange Server 中配置特定于客户端的消息大小限制 微软官方详细文档如下: https://learn.microsoft.com/zh-cn/exchange/architectu ...

  6. 使用 Cursor 和 Devbox 快速开发基于 Rust 的 WASM 智能合约

    本教程以一个智能合约(使用 NEAR 的一个官方 Fungible Tokens 来实现)的例子来介绍一下 Devbox 的强大功能,轻松构建环境,轻松发布. NEAR 是一个去中心化的应用平台,使用 ...

  7. 为什么会有unknown模块

    当一个模块在free后,他的线程仍然在运行时,会导致GetModuleName失败,返回unknown

  8. Redis的发布订阅Pub/Sub

    发布订阅 Redis 发布订阅(publish/subscribe)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息. Redis 客户端可以订阅任意数量的频道. 下图展示了频道 ...

  9. 批处理-- 查询进程,杀进程,启动pythond程序,任务计划程序

    @echo off wmic process where caption="python.exe" get processid,commandline | findstr &quo ...

  10. Next.js 与 React 全栈开发:整合 TypeScript、Redux 和 Ant Design

    在上一集,我们编写完毕导航页面,并且非常的美观,但是我们发现编写网站是存静态的,在现代的网站当中一般都是动静结合,也就是说部分数据是从数据库读取的,部分静态数据是写在网页上面的,因此这章讲述如何搭建一 ...