一、前言
在上一篇关于简化模式中,通过客户端以浏览器的形式请求IdentityServer服务获取访问令牌,从而请求获取受保护的资源,但由于token携带在url中,安全性方面不能保证。因此,我们可以考虑通过其他方式来解决这个问题。
我们通过Oauth2.0的授权码模式了解,这种模式不同于简化模式,在于授权码模式不直接返回token,而是先返回一个授权码,然后再根据这个授权码去请求token。这显得更为安全。
所以在这一篇中,我们将通过多种授权模式中的授权码模式进行说明,主要针对介绍IdentityServer保护API的资源,授权码访问API资源。
二、初识
(图片来源网络)
看一个常见的QQ登陆第三方网站的流程如下图所示:
2.1 适用范围
授权码模式(authorization code)是功能最完整、流程最严密的授权模式。
2.2 授权流程:
+----------+
| Resource |
| Owner |
| |
+----------+
^
|
(B)
+----|-----+ Client Identifier +---------------+
| -+----(A)-- & Redirection URI ---->| |
| User- | | Authorization |
| Agent -+----(B)-- User authenticates --->| Server |
| | | |
| -+----(C)-- Authorization Code ---<| |
+-|----|---+ +---------------+
| | ^ v
(A) (C) | |
| | | |
^ v | |
+---------+ | |
| |>---(D)-- Authorization Code ---------' |
| Client | & Redirection URI |
| | |
| |<---(E)----- Access Token -------------------'
+---------+ (w/ Optional Refresh Token)
授权码授权流程描述
(A)用户访问第三方应用,第三方应用将用户导向认证服务器;
(B)用户选择是否给予第三方应用授权;
(C)假设用户给予授权,认证服务器将用户导向第三方应用事先指定的重定向URI,同时带上一个授权码;
(D)第三方应用收到授权码,带上上一步时的重定向URI,向认证服务器申请访问令牌。这一步是在第三方应用的后台的服务器上完成的,对用户不可见;
(E)认证服务器核对了授权码和重定向URI,确认无误后,向第三方应用发送访问令牌(Access Token)和更新令牌(Refresh token);
(F)访问令牌过期后,刷新访问令牌;
2.2.1 过程详解
访问令牌请求
(1)用户访问第三方应用,第三方应用将用户导向认证服务器
(用户的操作:用户访问https://client.example.com/cb跳转到登录地址,选择授权服务器方式登录)
在授权开始之前,它首先生成state参数(随机字符串)。client端将需要存储这个(cookie,会话或其他方式),以便在下一步中使用。
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
HTTP/1.1 Host: server.example.com
生成的授权URL如上所述(如上),请求这个地址后重定向访问授权服务器,其中 response_type参数为code,表示授权类型,返回code授权码。
(2)假设用户给予授权,认证服务器将用户导向第三方应用事先指定的重定向URI,同时带上一个授权码
HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz
(3)第三方应用收到授权码,带上上一步时的重定向URI,向认证服务器申请访问令牌。这一步是在第三方应用的后台的服务器上完成的,对用户不可见。
POST /token HTTP/1.1
Host: server.example.com
Authorization: Bearer czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
(4)认证服务器核对了授权码和重定向URI,确认无误后,向第三方应用发送访问令牌(Access Token)和更新令牌(Refresh token)
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
"example_parameter":"example_value"
}
(5) 访问令牌过期后,刷新访问令牌
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA
三、实践
3.1 搭建 Authorization Server 服务
3.1.1 安装Nuget包
3.1.2 配置内容
建立配置内容文件Config.cs
public static class Config
{
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope("code_scope1")
};
public static IEnumerable<ApiResource> ApiResources =>
new ApiResource[]
{
new ApiResource("api1","api1")
{
Scopes={ "code_scope1" },
UserClaims={JwtClaimTypes.Role}, //添加Cliam 角色类型
ApiSecrets={new Secret("apipwd".Sha256())}
}
};
public static IEnumerable<Client> Clients =>
new Client[]
{
new Client
{
ClientId = "code_client",
ClientName = "code Auth",
AllowedGrantTypes = GrantTypes.Code,
RedirectUris ={
"http://localhost:5002/signin-oidc", //跳转登录到的客户端的地址
},
// RedirectUris = {"http://localhost:5002/auth.html" }, //跳转登出到的客户端的地址
PostLogoutRedirectUris ={
"http://localhost:5002/signout-callback-oidc",
},
ClientSecrets = { new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256()) },
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"code_scope1"
},
//允许将token通过浏览器传递
AllowAccessTokensViaBrowser=true,
// 是否需要同意授权 (默认是false)
RequireConsent=true
}
};
}
因为是授权码授权的方式,所以我们通过代码的方式来创建几个测试用户。
新建测试用户文件TestUsers.cs
public class TestUsers
{
public static List<TestUser> Users
{
get
{
var address = new
{
street_address = "One Hacker Way",
locality = "Heidelberg",
postal_code = 69118,
country = "Germany"
};
return new List<TestUser>
{
new TestUser
{
SubjectId = "1",
Username = "i3yuan",
Password = "123456",
Claims =
{
new Claim(JwtClaimTypes.Name, "i3yuan Smith"),
new Claim(JwtClaimTypes.GivenName, "i3yuan"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "i3yuan@email.com"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.WebSite, "http://i3yuan.top"),
new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)
}
}
};
}
}
}
返回一个TestUser的集合。
通过以上添加好配置和测试用户后,我们需要将用户注册到IdentityServer4服务中,接下来继续介绍。
3.1.3 注册服务
在startup.cs中ConfigureServices方法添加如下代码:
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddIdentityServer()
.AddTestUsers(TestUsers.Users); //添加测试用户
// in-memory, code config
builder.AddInMemoryIdentityResources(Config.IdentityResources);
builder.AddInMemoryApiScopes(Config.ApiScopes);
builder.AddInMemoryApiResources(Config.ApiResources);
builder.AddInMemoryClients(Config.Clients);
// not recommended for production - you need to store your key material somewhere secure
builder.AddDeveloperSigningCredential();
services.ConfigureNonBreakingSameSiteCookies();
}
3.1.4 配置管道
在startup.cs中Configure方法添加如下代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
以上内容是快速搭建简易IdentityServer项目服务的方式。
这搭建 Authorization Server 服务跟上一篇简化模式有何不同之处呢?
3.2 搭建API资源
3.2.1 快速搭建一个API项目
3.2.2 安装Nuget包
3.2.3 注册服务
在startup.cs中ConfigureServices方法添加如下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5001";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
options.ApiSecret = "apipwd"; //对应ApiResources中的密钥
});
}
AddAuthentication把Bearer配置成默认模式,将身份认证服务添加到DI中。
AddIdentityServerAuthentication把IdentityServer的access token添加到DI中,供身份认证服务使用。
3.2.4 配置管道
在startup.cs中Configure方法添加如下代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
UseAuthentication将身份验证中间件添加到管道中;
UseAuthorization 将启动授权中间件添加到管道中,以便在每次调用主机时执行身份验证授权功能。
3.2.5 添加API资源接口
[Route("api/[Controller]")]
[ApiController]
public class IdentityController:ControllerBase
{
[HttpGet("getUserClaims")]
[Authorize]
public IActionResult GetUserClaims()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
在IdentityController 控制器中添加 [Authorize] , 在进行请求资源的时候,需进行认证授权通过后,才能进行访问。
3.3 搭建MVC 客户端
3.3.1 快速搭建一个MVC项目
3.3.2 安装Nuget包
3.3.3 注册服务
要将对 OpenID Connect 身份认证的支持添加到MVC应用程序中。
在startup.cs中ConfigureServices方法添加如下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthorization();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies") //使用Cookie作为验证用户的首选方式
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "http://localhost:5001"; //授权服务器地址
options.RequireHttpsMetadata = false; //暂时不用https
options.ClientId = "code_client";
options.ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A";
options.ResponseType = "code"; //代表Authorization Code
options.Scope.Add("code_scope1"); //添加授权资源
options.SaveTokens = true; //表示把获取的Token存到Cookie中
options.GetClaimsFromUserInfoEndpoint = true;
});
services.ConfigureNonBreakingSameSiteCookies();
}
3.3.4 配置管道
然后要确保认证服务执行对每个请求的验证,加入UseAuthentication
和UseAuthorization
到Configure
中,在startup.cs中Configure方法添加如下代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
3.3.5 添加授权
在HomeController控制器并添加[Authorize]
特性到其中一个方法。在进行请求的时候,需进行认证授权通过后,才能进行访问。
[Authorize]
public IActionResult Privacy()
{
ViewData["Message"] = "Secure page.";
return View();
}
还要修改主视图以显示用户的Claim以及cookie属性。
@using Microsoft.AspNetCore.Authentication
<h2>Claims</h2>
<dl>
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
</dl>
<h2>Properties</h2>
<dl>
@foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
{
<dt>@prop.Key</dt>
<dd>@prop.Value</dd>
}
</dl>
访问 Privacy 页面,跳转到认证服务地址,进行账号密码登录,Logout 用于用户的注销操作。
3.3.6 添加资源访问
在HomeController
控制器添加对API资源访问的接口方法。在进行请求的时候,访问API受保护资源。
/// <summary>
/// 测试请求API资源(api1)
/// </summary>
/// <returns></returns>
public async Task<IActionResult> getApi()
{
var client = new HttpClient();
var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
if (string.IsNullOrEmpty(accessToken))
{
return Json(new { msg = "accesstoken 获取失败" });
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var httpResponse = await client.GetAsync("http://localhost:5003/api/identity/GetUserClaims");
var result = await httpResponse.Content.ReadAsStringAsync();
if (!httpResponse.IsSuccessStatusCode)
{
return Json(new { msg = "请求 api1 失败。", error = result });
}
return Json(new
{
msg = "成功",
data = JsonConvert.DeserializeObject(result)
});
}
3.4 效果
3.4.1 动图
3.4.2 过程
在用户访问MVC程序时候,将用户导向认证服务器,
在客户端向授权服务器Authorization Endpoint
进行验证的时候,我们可以发现,向授权服务器发送的请求附带的那些参数就是我们之前说到的数据(clientid,redirect_url,type等)
继续往下看,发现在用户给予授权完成登录之后,可以看到在登录后,授权服务器向重定向URL地址同时带上一个授权码数据带给MVC程序。
随后MVC向授权客户端的Token终结点发送请求,从下图可以看到这次请求包含了client_id,client_secret,code,grant_type和redirect_uri,向授权服务器申请访问令牌token, 并且在响应中可以看到授权服务器核对了授权码和重定向地址URI,确认无误后,向第三方应用发送访问令牌(Access Token)和更新令牌(Refresh token)
完成获取令牌后,访问受保护资源的时候,带上令牌请求访问,可以成功响应获取用户信息资源。
四、总结
- 本篇主要阐述以授权码授权,编写一个MVC客户端,并通过客户端以浏览器的形式请求IdentityServer上请求获取访问令牌,从而访问受保护的API资源。
- 授权码模式解决了简化模式由于token携带在url中,安全性方面不能保证问题,而通过授权码的模式不直接返回token,而是先返回一个授权码,然后再根据这个授权码去请求token,这个请求token这个过程需要放在后台,这种方式也更为安全。适用于有后端的应用。
- 在后续会对这方面进行介绍继续说明,数据库持久化问题,以及如何应用在API资源服务器中和配置在客户端中,会进一步说明。
- 如果有不对的或不理解的地方,希望大家可以多多指正,提出问题,一起讨论,不断学习,共同进步。
- 项目地址