IdentityServer4:簡化(隱式)模式
簡化(隱式)模式流程是:
用戶從客戶端跳轉到認證服務器,然後輸入用戶名和密碼, 密碼驗證通過後,進入授權界面,選擇授權範圍,最後同意後才跳轉回客戶端頁面。而在返回的跳轉Url鏈接中包含了:id_token 和 access_token, 客戶端就是從這個返回的Url中提取到 access_token。
故:簡化(隱式)模式模式比較適用於純前端項目、微信開發等,比如前後端分離的項目中的 Vue、Angual、Rect 純前端項目。
Api 資源項目
創建項目
打開 VS,創建一個“AspNet Core WebApi” 項目, 名爲:Dotnet.WebApi.Ids4.CustomerApi
依賴包
添加依賴包
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.3" />
添加認證方案
修改 Program.cs 爲如下代碼:
using Microsoft.AspNetCore.Authentication.JwtBearer;
namespace Dotnet.WebApi.Ids4.CustomerApi
{
public class Program
{
public static void Main(string[] args)
{
Console.Title = "CustomerAPI服務器";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//IdentityServer4地址
options.Authority = "https://localhost:6001";
//認證的ApiResource名稱
options.Audience = "CustomerAPIResource";
//使用JWT認證類型
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
});
//配置跨域。
builder.Services.AddCors(options =>
{
options.AddPolicy("AppCors", policy => policy.WithOrigins("https://localhost:6021")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
);
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.Urls.Add("https://*:6011");
app.UseHttpsRedirection();
//啓用跨域中間件
app.UseCors("AppCors");
//身份驗證
app.UseAuthentication();
//授權
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
其中,
(1)添加 JWT 認證:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//IdentityServer4地址
options.Authority = "https://localhost:6001";
//認證的ApiResource名稱
options.Audience = "CustomerAPIResource";
//使用JWT認證類型
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
});
https://localhost:6001 是認證服務器地址。
(2) 純前端項目存在跨域問題,故這裏資源服務器爲純前端項目提供跨域支持。
//配置跨域。
builder.Services.AddCors(options =>
{
options.AddPolicy("AppCors", policy => policy.WithOrigins("https://localhost:6021")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
);
});
app.UseCors("AppCors");
這裏,我們先假設純前端項目的地址爲:https://localhost:6021
添加 Api
新增文件:Controllers/CustomerController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Dotnet.WebApi.Ids4.CustomerApi.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
/// <summary>
/// 獲取客戶信息列表。
/// </summary>
/// <returns></returns>
[HttpGet("GetList")]
public IEnumerable<Customer> GetList()
{
return new List<Customer>
{
new Customer{ Id=1, Name="客戶1", Phone="電話1"},
new Customer{ Id=2, Name="客戶2", Phone="電話2"},
new Customer{ Id=3, Name="客戶3", Phone="電話3"},
};
}
}
}
其中:
(1)在控制器上添加特性:[Authorize],這樣只有登錄用戶才能訪問,這樣就起到保護了Api資源的目的。
Customer.cs
namespace Dotnet.WebApi.Ids4.CustomerApi
{
/// <summary>
/// 客戶實體模型
/// </summary>
public class Customer
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Phone { get; set; }
}
}
認證服務器
創建項目
打開 VS,創建一個“AspNet Core 空” 項目,名爲:Dotnet.WebApi.Ids4.AuthService
依賴包
添加依賴包
<PackageReference Include="IdentityServer4" Version="4.1.2" />
配置 IdentityServer4
創建文件:IdentityConfig.cs,添加如下代碼:
using IdentityModel;
using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System.Security.Claims;
namespace Dotnet.WebApi.Ids4.AuthService
{
public static class IdentityConfig
{
/// <summary>
/// 配置IdentityResource。
/// </summary>
/// <returns></returns>
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource> {
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
}
/// <summary>
/// 配置API作用域。
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiScope> GetApiScopes()
{
return new List<ApiScope>
{
//客戶相關API作用域
new ApiScope("Customer.Read","讀取客戶信息。"),
new ApiScope("Customer.Add","添加客戶信息。"),
//共享API作用域
new ApiScope("News","新聞信息。")
};
}
/// <summary>
/// 配置ApiResource。
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources()
{
//將多個具體的APIScope歸爲一個ApiResource。
return new List<ApiResource>()
{
new ApiResource("CustomerAPIResource", "客戶資源")
{
Scopes={ "Customer.Read", "Customer.Add", "News" }
}
};
}
/// <summary>
/// 配置客戶端應用。
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
#region 簡化(隱式)模式
return new List<Client>
{
new Client
{
//客戶端ID。
ClientId="WebClient",
//客戶端名稱。
ClientName="Web客戶端",
//授權模式爲Implicit,表示簡化授權模式。
AllowedGrantTypes=GrantTypes.Implicit,
//授權操作頁面支持,爲true表示顯示授權界面,否則不顯示。
RequireConsent=true,
//身份認證成功之後重定向到客戶端的回調地址。
RedirectUris={ "https://localhost:6021/callback.html"},
//退出時重定向到客戶端的地址。
PostLogoutRedirectUris={"https://localhost:6021/home.html"},
//允許跨域操作,設置允許跨域的客戶端地址。
AllowedCorsOrigins={"https://localhost:6021"},
//允許瀏覽器傳遞AccessToken。
AllowAccessTokensViaBrowser=true,
//設置AccessToken能訪問的作用域。
AllowedScopes={
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"Customer.Read" ,//可訪問的API。
}
}
};
#endregion
}
/// <summary>
/// 配置用戶。
/// </summary>
/// <returns></returns>
public static List<TestUser> GetUsers()
{
#region 簡化模式
return new List<TestUser>
{
new TestUser
{
SubjectId="00001",
Username="Kevin",
Password="123456",
//添加聲明信息
Claims =
{
new Claim(JwtClaimTypes.Name, "Kevin"),
new Claim(JwtClaimTypes.GivenName, "Mi"),
new Claim(JwtClaimTypes.FamilyName, "Kala"),
new Claim(JwtClaimTypes.Email, "[email protected]"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean)
}
}
};
#endregion
}
}
}
代碼解析:
(1)簡化模式通過在客戶端和認證服務器往返的URL來傳遞數據,使用了 Openid Connect 協議,故得在IdentityServer中配置 Openid 信息, 這是簡化模式必須得添加的:
/// <summary>
/// 配置IdentityResource。
/// </summary>
/// <returns></returns>
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource> {
new IdentityResources.OpenId(),
};
}
如果需要客戶端要求能獲取到用戶信息,還得添加new IdentityResources.Profile()
, 如下所示:
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource> {
new IdentityResources.OpenId(),
+ new IdentityResources.Profile()
};
}
(2)如下代碼添加了 Client,並將其授權模式設置爲:簡化模式, 並設置密碼,和 Scope:
new Client
{
//客戶端ID。
ClientId="WebClient",
//客戶端名稱。
ClientName="Web客戶端",
//授權模式爲Implicit,表示簡化授權模式。
AllowedGrantTypes=GrantTypes.Implicit,
//授權操作頁面支持,爲true表示顯示授權界面,否則不顯示。
RequireConsent=true,
//身份認證成功之後重定向到客戶端的回調地址。
RedirectUris={ "https://localhost:6021/callback.html"},
//退出時重定向到客戶端的地址。
PostLogoutRedirectUris={"https://localhost:6021/home.html"},
//允許跨域操作,設置允許跨域的客戶端地址。
AllowedCorsOrigins={"https://localhost:6021"},
//允許瀏覽器傳遞AccessToken。
AllowAccessTokensViaBrowser=true,
//設置AccessToken能訪問的作用域。
AllowedScopes={
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"Customer.Read" ,//可訪問的API。
}
}
其中:
(1)設置授權模式:AllowedGrantTypes=GrantTypes.Implicit
(2)身份認證成功之後重定向到客戶端的回調地址: RedirectUris={ "https://localhost:6021/callback.html"},
(3)退出時重定向到客戶端的地址:PostLogoutRedirectUris={"https://localhost:6021/home.html"},
(4)跨域支持: AllowedCorsOrigins={"https://localhost:6021"},
(5)設置Scope:AllowedScopes = { ... }
(3) 添加用戶:因爲簡化模式需要用戶參與,故得添加用戶;
return new List<TestUser>
{
new TestUser
{
SubjectId="00001",
Username="Kevin",
Password="123456",
//添加聲明信息
Claims =
{
new Claim(JwtClaimTypes.Name, "Kevin"),
new Claim(JwtClaimTypes.GivenName, "Mi"),
new Claim(JwtClaimTypes.FamilyName, "Kala"),
new Claim(JwtClaimTypes.Email, "[email protected]"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean)
}
}
};
集成 IdentityServer4
添加 IdentityServer4的Quickstart UI
因爲簡化(隱式)模式流程是:
用戶從客戶端跳轉到認證服務器,然後輸入用戶名和密碼, 密碼驗證通過後,進入授權界面,選擇授權範圍,最後同意後才跳轉回客戶端頁面。
在返回的跳轉鏈接中包含了:id_token 和 access_token, 客戶端就是從這個返回的Url中提取到 access_token。
從以上過程可以看到,IdentityServer4 認證服務器得有一個界面,好在已經一個開源項目:Quickstart UI,可以直接用即可。
下載 Quickstart UI:https://github.com/IdentityServer/IdentityServer4.Quickstart.UI,
然後把 Quickstart、Views、wwwroot 三個文件夾複製到 Dotnet.WebApi.Ids4.AuthService 項目根目錄下。
由於 Quickstart UI 使用了 AspNet Core 的 MVC 框架,所以得在 Program.cs 開啓 MVC 框架:
//註冊MVC服務。
builder.Services.AddControllersWithViews();
......
//終結點
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
Program.cs
修改 Program.cs 爲如下代碼:
namespace Dotnet.WebApi.Ids4.AuthService
{
public class Program
{
public static void Main(string[] args)
{
Console.Title = "認證和授權服務器";
var builder = WebApplication.CreateBuilder(args);
//註冊MVC服務。
builder.Services.AddControllersWithViews();
//註冊IdentityServer4組件
builder.Services.AddIdentityServer()
.AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
.AddInMemoryApiScopes(IdentityConfig.GetApiScopes())
.AddInMemoryApiResources(IdentityConfig.GetApiResources())
.AddInMemoryClients(IdentityConfig.GetClients())
.AddTestUsers(IdentityConfig.GetUsers())
.AddDeveloperSigningCredential(); // 添加臨時內存中的證書
var app = builder.Build();
//修改端口號
app.Urls.Add("https://*:6001");
//啓用靜態文件
app.UseStaticFiles();
//啓用HTTPS轉向
app.UseHttpsRedirection();
//啓用路由
app.UseRouting();
//添加IDS4中間件。
//在瀏覽器中輸入如下地址訪問 IdentityServer4 的發現文檔:https://localhost:6001/.well-known/openid-configuration
app.UseIdentityServer();
//授權
app.UseAuthorization();
//終結點
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
}
}
其中,app.Urls.Add("https://*:6001");
設置認證服務器的監聽端口爲:6001
簡化(隱式)模式客戶端
創建項目
創建一個 “AspNet Core 空項目”,名爲:Dotnet.WebApi.ImplicitClient。這個項目沒用到 AspNet Core 的任何功能,僅僅只是作爲一個靜態文件站點,即:一個純前端項目。
添加 JS 庫
創建"wwwroot"文件夾,然後選擇該文件夾,右鍵【添加/客戶端庫】,添加bootract.min.css
、jquery.min.js
、 oidc-client.js
文件。
其中:oidc-client.js
庫用來處理 Openid connect 登錄、獲取保存AccesssToken、登出等功能。
創建頁面:home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>簡化(隱式)模式 - Web客戶端</title>
<link href="/bootstrap/css/bootstrap.css" rel="stylesheet" />
<script src="jquery/jquery.js"></script>
<script src="oidc-client/oidc-client.js"></script>
</head>
<body>
<div style="margin:20px;">
<input type="button" class="btn btn-primary" onclick="login()" value="登錄" />
<input type="button" class="btn btn-primary" onclick="CallApi()" value="調用API" />
<input type="button" class="btn btn-primary" onclick="Signout()" value="退出" />
</div>
<div id="apiData" style="margin:20px;"></div>
<script>
//客戶端配置。
this.config = {
authority: "https://localhost:6001",
client_id: "WebClient",
redirect_uri: "https://localhost:6021/callback.html",
response_type: "id_token token",
scope: "openid profile Customer.Read", //訪問權限範圍。
post_logout_redirect_uri: "https://localhost:6021/home.html",
};
//根據配置信息創建用戶管理對象。
this.userManager = new Oidc.UserManager(this.config);
//登錄
function login() {
//跳轉到IDS4的登錄頁面。
this.userManager.signinRedirect();
this.userManager.getUser().then(function (user) {
if (user) { //如果登錄,在瀏覽器控制檯輸出用戶信息。
console.log(user.profile)
} else { //如果未登錄,則提示請登錄。
console.log("請登錄");
}
});
}
//調用API
function CallApi() {
var that = this;
//登錄成功之後有了access_token,就可以調用API資源服務器上的API了。
this.userManager.getUser().then(function (user) {
//要調用的API資源URL地址。
var url = 'https://localhost:6011/api/customer/getlist';
var r = '';
$.ajax({
type: 'get',
contentType: 'application/json',
url: url,
beforeSend: function (xhr) {
//獲取Token
var accessToken = user.access_token;
//使用Token請求資源
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
},
//獲取的數據[{},{},{}]
success: function (data) {
$.each(data, function (n, value) {
r += "<p>ID:" + value.id + "</p>" +
"<p>Name:" + value.name + "</p>" +
"<p>Phone:" + value.phone + "</p>";
$("#apiData").html(r);
});
},
error: function (xhr) {
console.log(xhr.statusCode);
}
})
});
}
//退出
function Signout() {
this.userManager.signoutRedirect();
}</script>
</body>
</html>
創建頁面:callback.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>回調頁面</title>
<script src="jquery/jquery.js"></script>
<script src="oidc-client/oidc-client.js"></script>
</head>
<body>
<h3>這是回調頁面。</h3>
<script>//獲取回調後的用戶信息。
new Oidc.UserManager().signinRedirectCallback().then(function (user) {
console.log(user);
var u = "<p>AccessToken:" + user.access_token + "</p>" +
"<p>IdToken:" + user.id_token + "</p>" +
"<p>Scope:" + user.scope + "</p>" +
"<p>SessionState:" + user.session_state + "</p>" +
"<p>UserName:" + user.profile.name + "</p>";
$("#userInfo").html(u);
}).catch(function (e) {
console.log(e);
});</script>
<h3>從服務器拿來的信息如下:</h3>
<div id="userInfo"></div>
<hr />
<div>
<a href="home.html">回到首頁</a>
</div>
</body>
</html>
Program.cs
將 Program.cs 的代碼修改爲;
namespace Dotnet.WebApi.ImplicitClient
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Urls.Add("https://*:6021");
//啓用靜態文件
app.UseStaticFiles();
app.Run();
}
}
}
只是啓用靜態文件中間件,作爲一個純前端客戶端。
運行結果
訪問客戶端主頁:https://localhost:6021/home.html
點擊【登錄】按鈕,跳轉到 IdentityServer4 認證服務器,
此時的 Url 爲:
https://localhost:6001/Account/Login?ReturnUrl=/connect/authorize/callback?client_id=WebClient&redirect_uri=https://localhost:6021/callback.html&response_type=id_token token&scope=openid profile Customer.Read&state=0f388a11a35d484382298f04064f6f4c&nonce=cbee67183fb84a2b9546880028f51af8
Url中包含了 OAuth2.0 協議的簡化(隱式)模式規定的相關參數,比如:
- ReturnUrl=/connect/authorize/callback
- client_id=WebClient
- redirect_uri=https://localhost:6021/callback.html
- response_type=id_token token
- scope=openid profile Customer.Read
- state=0f388a11a35d484382298f04064f6f4c&nonce=cbee67183fb84a2b9546880028f51af8
輸入用戶名和密碼,點擊登錄:
然後跳轉到授權頁面:
https://localhost:6001/consent?returnUrl=/connect/authorize/callback?client_id=WebClient&redirect_uri=https://localhost:6021/callback.html&response_type=id_token token&scope=openid profile Customer.Read&state=0f388a11a35d484382298f04064f6f4c&nonce=cbee67183fb84a2b9546880028f51af8
點擊【Yes, Allow】進行授權。
授權成功後,返回客戶端頁面,返回的Url爲:
https://localhost:6021/callback.html#id_token=eyJhbGciOiJSUzI1NiIsImtpZCI6IkJBRUUyOEI1NkFDNTFFMjI0RTgxQjE0OTI2RTU5REEwIiwidHlwIjoiSldUIn0.eyJuYmYiOjE2NzgzNTI4MDUsImV4cCI6MTY3ODM1M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kiOiJCNDVCNzkwRjE2N0EzQzIwRERGQjk0MThEQzRBQUY1MiIsInNpZCI6IkU0RkIwRjNDNTA2RDNFNTRGRkM2M0EyN0Q1ODE0MDU0IiwiaWF0IjoxNjc4MzUyODA1LCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiQ3VzdG9tZXIuUmVhZCJdLCJhbXIiOlsicHdkIl19.OuOX-T10L0bKLOgWFMrVobzHFW4I-Qnvn-3jwV70ECQNKCKd3Bx3dN4_xgf4G4wox7gE2iXMVnOPPvllNYPPxyBaHj9lve3GiAng8EKGFVWe5sbvJAu_HPdPT0I0LmckTShNDi6HgBlevmTPzROLH_7bGg3jTpwQRBuZhJgaWxE29Fbqw6CynZTI22hsthPK0m66XGSz8o8ilpscFa04e6fxvvl-lmKK9O1mZzTBSi1DLbFsHAo1fMwgp5aMEcM7tAx5oSveJT7-lQIm7LSY6ZXz24sAcmZNEtJsdbzrOnpaK855ccE4IrHRRk18Spfy0haVKPC-hhLhbdyIZ_VnVA&token_type=Bearer&expires_in=3600&scope=openid profile Customer.Read&state=0f388a11a35d484382298f04064f6f4c&session_state=MmClIQIFgr0c_5qWPakrECkXpxGEHmghpjm_Z3mMibY.BF41E23BC65E6DC036F72B546E70122F
我們可以看到:返回的Url中包含了Openid Connect 協議和 OAuth2.0 協議的相關參數,比如:
- id_token=eyJhbGciOiJ...
- access_token=yJhbGciOi...
- token_type=Bearer
- scope=openid profile Customer.Read
- expires_in=3600
- state=0f388a11a35d484382298f04064f6f4c
最後返回到主頁,點擊【調用API】按鈕,我們可以看到通過 AccessToken 訪問資源服務受保護的數據: