Duende Identity Server学习之一:认证服务器及一个Oidc/OAuth认证、用于Machine 2 Machine的客户端
这是一个学习Duende Identity Server的系列。这是.Net社区有名的项目,提供了基于OIDC/OAuth的服务器方案。当然这个库已经不再免费,但是对个人项目依旧免费——前提是只能使用其Debug的分支。
本篇是这个系列的第一篇,是一个非常简单的场景——认证服务器及一个Oidc/OAuth认证、用于Machine 2 Machine的客户端。换言之,这个项目无需用户登录。这个项目包含三个子项目:
- 认证服务器;
- MyAPI;一个需要权限才能访问的API;
- ClientConsole:一个允许访问MyAPI的客户端;
本文需要.Net的基础知识。
本文所有代码存放的Repository见文章底部。
前期准备
- 安装.Net 模板 (注意:模板Duende.IdentityServer.Templates 已经过期!).
dotnet new install Duende.Templates
- 在当前文件夹下创建一个.NET Solution文件。
dotnet new sln -n LearnIDServer
- 在当前文件夹下,创建子目录
src
.
创建认证服务器 IdentityServer
创建认证服务器 IdentityServer
,将其放在子目录 src
下,并将其加入Solution文件:
dotnet new duende-is-empty -n IdentityServer
cd ..
dotnet sln add ./src/IdentityServer
修改 config.cs
和HostingExtension.cs
文件
接着,更新类 ApiScope
,Client
,这两个类定义在Config.cs
中.
public static IEnumerable<ApiScope> ApiScopes =>new ApiScope[]{new ApiScope(name: "api1", displayName: "My API")};public static IEnumerable<Client> Clients =>new Client[]{new Client{ClientId = "client",// no interactive user, use the clientid/secret for authenticationAllowedGrantTypes = GrantTypes.ClientCredentials,// secret for authenticationClientSecrets ={new Secret("secret".Sha256())},// scopes that client has access toAllowedScopes = { "api1" }}};
代码解读,上述代码定义了一个C