一. 前言
1.简介
授权码模式(authorization code)是功能最完整、流程最严密的授权模式。它的特点就是通过客户端的后台服务器,与"服务提供商"的认证服务器进行互动。
2. 流程图
流程
(A)用户访问客户端,后者将前者导向认证服务器。
(B)用户选择是否给予客户端授权。
(C)假设用户给予授权,认证服务器将用户导向客户端事先指定的"重定向URI"(redirection URI),同时附上一个授权码。
(D)客户端收到授权码,附上早先的"重定向URI",向认证服务器申请令牌。这一步是在客户端的后台的服务器上完成的,对用户不可见。
(E)认证服务器核对了授权码和重定向URI,确认无误后,向客户端发送访问令牌(access token)和更新令牌(refresh token)。
(F) 拿到令牌后,可以尽情的请求资源服务器了。
3. 流程剖析
步骤A:导向认证服务器,如下请求,进而再导向认证服务器的登录页面。
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
Host: server.example.com
参数包括:
response_type:表示授权类型,此处的值固定为"code",必选项。
client_id:表示客户端的ID,必选项。
redirect_uri:表示重定向的URI,可选项。
scope:表示权限范围,可选项。
state:表示客户端的当前状态,可以指定任意值,认证服务器会原封不动地返回这个值。
步骤C:服务器回应客户端的URI
Location https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz
参数包括:
code:表示授权码,必选项。该码的有效期应该很短,通常设为10分钟,客户端只能使用该码一次,否则会被授权服务器拒绝。该码与客户端ID和重定向URI,是一一对应关系。
state:如果客户端的请求中包含这个参数,认证服务器的回应也必须一模一样包含这个参数。
步骤D:客户端携带授权码code像认证服务器申请令牌,这一步一般是封装代码实现,看不到具体代码。
Content-Type: application/x-www-form-urlencoded
POST /authorize?grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
参数包括:
grant_type:表示使用的授权模式,必选项,此处的值固定为"authorization_code"。
code:表示上一步获得的授权码,必选项。
redirect_uri:表示重定向URI,必选项,且必须与A步骤中的该参数值保持一致。
client_id:表示客户端ID,必选项。
步骤E:认证服务器返回令牌等信息。
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"example",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
"example_parameter":"example_value"
}
参数包括:
access_token:表示访问令牌,必选项。
token_type:表示令牌类型,该值大小写不敏感,必选项,可以是bearer类型或mac类型。
expires_in:表示过期时间,单位为秒。如果省略该参数,必须其他方式设置过期时间。
refresh_token:表示更新令牌,用来获取下一次的访问令牌,可选项。
scope:表示权限范围,如果与客户端申请的范围一致,此项可省略。
二. 代码实操演练
1. 项目准备
(1). ID4_Server2:授权认证服务器 【地址:http://127.0.0.1:7070】
(2). MvcCodeClient2:web性质的客户端 【地址:http://127.0.0.1:7072】
2. 搭建步骤
(一). ID4_Server2
(1).通过Nuget安装【IdentityServer4 4.0.2】程序集
(2).集成IDS4官方的UI页面
进入ID4_Server2的根目录,cdm模式下依次输入下面指令,集成IDS4相关的UI页面,发现新增或改变了【Quickstart】【Views】【wwwroot】三个文件夹
A.【dotnet new -i identityserver4.templates】
B.【dotnet new is4ui --force】 其中--force代表覆盖的意思, 空项目可以直接输入:【dotnet new is4ui】,不需要覆盖。
PS. 有时候正值版本更新期间,上述指令下载下来的文件可能不是最新的,这个时候只需要手动去下载,然后把上述三个文件夹copy到项目里即可
(下载地址:https://github.com/IdentityServer/IdentityServer4.Quickstart.UI)
(3).创建Config2配置类,进行可以使用IDS4资源的配置
A.授权码模式: AllowedGrantTypes = GrantTypes.Code,
B.授权成功返回的地址:RedirectUris = { "http://127.0.0.1:7072/signin-oidc" }, 7072是MvcCodeClient2客户端的端口,signin-oidc是IDS4监听的一个地址,可以拿到token信息。
代码分享:
public class Config2 { /// <summary> /// IDS资源 /// </summary> /// <returns></returns> public static IEnumerable<IdentityResource> GetIds() { return new List<IdentityResource> { new IdentityResources.OpenId(), new IdentityResources.Profile(), }; } /// <summary> /// 可以使用ID4 Server 客户端资源 /// </summary> /// <returns></returns> public static IEnumerable<Client> GetClients() { List<Client> clients = new List<Client>() { new Client { ClientId = "client1", ClientSecrets = { new Secret("123456".Sha256()) }, //授权码模式 AllowedGrantTypes = GrantTypes.Code, //需要确认授权 RequireConsent = true, RequirePkce = true, //允许token通过浏览器 AllowAccessTokensViaBrowser=true, // where to redirect to after login(登录) RedirectUris = { "http://127.0.0.1:7072/signin-oidc" }, // where to redirect to after logout(退出) PostLogoutRedirectUris = { "http://127.0.0.1:7072/signout-callback-oidc" }, //允许的范围 AllowedScopes = new List<string> { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile }, AlwaysIncludeUserClaimsInIdToken=true } }; return clients; } /// <summary> /// 定义可以使用ID4的用户资源 /// </summary> /// <returns></returns> public static List<TestUser> GetUsers() { var address = new { street_address = "One Hacker Way", locality = "Heidelberg", postal_code = 69118, country = "Germany" }; return new List<TestUser>() { new TestUser { SubjectId = "001", Username = "ypf1", //账号 Password = "123456", //密码 Claims = { new Claim(JwtClaimTypes.Name, "Alice Smith"), new Claim(JwtClaimTypes.GivenName, "Alice"), new Claim(JwtClaimTypes.FamilyName, "Smith"), new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"), new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean), new Claim(JwtClaimTypes.WebSite, "http://alice.com"), new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json) } }, new TestUser { SubjectId = "002", Username = "ypf2", Password = "123456", Claims = { new Claim(JwtClaimTypes.Name, "Bob Smith"), new Claim(JwtClaimTypes.GivenName, "Bob"), new Claim(JwtClaimTypes.FamilyName, "Smith"), new Claim(JwtClaimTypes.Email, "BobSmith@email.com"), new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean), new Claim(JwtClaimTypes.WebSite, "http://bob.com"), //这是新的序列化模式哦 new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json) } } }; }