IdentityServer简介(摘自Identity官网)
IdentityServer是将符合规范的OpenID Connect和OAuth 2.0端点添加到任意ASP.NET核心应用程序的中间件,通常,您构建(或重新使用)一个包含登录和注销页面的应用程序(可能还包括同意,具体取决于您的需要),IdentityServer中间件向其添加必要的协议头,以便客户端应用程序可以使用这些标准协议与之对话。
托管应用程序可以像您希望的那样复杂,但我们通常建议通过只包含与身份验证相关的UI来尽可能地保持攻击面小。
client :客户端,从identityServer请求令牌,用户对用户身份校验,客户端必须先从identityServer中注册,然后才能请求令牌。
sources :每个资源都有自己唯一的名称,就是文中所定义的api1服务名称,indentity会验证判定是否有访问该资源的权限。
access Token :访问令牌,由identityServer服务器签发的,客户端使用该令牌进行访问拥有权限的api
OAuth 2.0四种授权模式(GrantType)
- 客户端模式(client_credentials)
- 密码模式(password)
- 授权码模式(authorization_code)
- 简化模式(implicit)
作用
- 单点登录
在多个应用程序当中进行统一登录或者注销。
- api访问控制
- 为各种类型的客户端(如服务器到服务器、Web应用程序、SPA和本机/移动应用程序)颁发API访问令牌。
- 联盟网关
支持外部身份提供商,如Azure Active Directory、Google、Facebook等。这将使您的应用程序不了解如何连接到这些外部提供商的详细信息。
开发准备
开发环境 :vs2019
identityServer4:2.4.0
netcore版本 :2.1
客户端授权模式介绍
客户端模式的话是属于identityServer保护API的最基础的方案,我们定义个indentityServer服务以及一个需要保护的API服务,
当客户端直接访问api的话,由于我们的api服务添加了authorization认证,所以必须要到identityServer放服务器上拿到访问令牌,客户端凭借该令牌去对应api服务当中获取想要得到的数据。
添加IdentityServer项目
1.首先添加新项目,创建ASP.NET Core Web 应用程序 创建一个名称为identityServer4test的项目,选择项目类型API 项目进行创建。
2.从程序包管理器控制台或者ngGet下载IdentityServer4
2.1 程序包管理器控制台:install-package IdentityServer4
2.2 NuGet 的话在对应的程序集,选择nuget输入IdentityServer4选择对应的版本进行下载安装
3.添加Identity Server4 配置
资源定义可以通过多种方式实现,具体的请查阅官方api文档:https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html
注:1.ApiResource("api1","My Api"),其中api1代表你的唯一资源名称,在 AllowedScopes = { "api1" }当中必须配置上才可以进行访问
using IdentityServer4.Models; using IdentityServer4.Test; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4Test.IndntityConfig { public class IdentityServerConfig { /// <summary> /// 添加api资源 /// </summary> /// <returns></returns> public static IEnumerable<ApiResource> GetResources() { return new List<ApiResource> {
new ApiResource("api1","My Api") }; } /// <summary> /// 添加客户端,定义一个可以访问此api的客户端 /// </summary> /// <returns></returns> public static IEnumerable<Client> GetClients() { return new List<Client> { new Client { /// ClientId = "client", // 没有交互性用户,使用 客户端模式 进行身份验证。 AllowedGrantTypes = GrantTypes.ClientCredentials, // 用于认证的密码 ClientSecrets = { new Secret("123454".Sha256()) }, // 客户端有权访问的范围(Scopes) AllowedScopes = { "api1" } } }; } } }
4.在startUp当中注入IdentityServer4 服务
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServe