接上一篇:IdentityServer4實現OAuth2.0四種模式之密碼模式,密碼模式將用戶的密碼暴露給了客戶端,這無疑是不安全的,隱藏模式可以解決這個問題,由用戶自己在IdentityServer服務器進行登錄驗證,客戶端不需要知道用戶的密碼。
一,服務端配置
1,添加客戶端:在IentityServer項目添加一個客戶端用於支持隱藏模式訪問。隱藏模式只需要用戶登錄驗證,不需要客戶端密碼。
IdentityServer.Config.Getlients
public static IEnumerable<Client> GetClients()
{
return new Client[] {
new Client()
{
//客戶端Id
ClientId="apiClientCd",
//客戶端密碼
ClientSecrets={new Secret("apiSecret".Sha256()) },
//客戶端授權類型,ClientCredentials:客戶端憑證方式
AllowedGrantTypes=GrantTypes.ClientCredentials,
//允許訪問的資源
AllowedScopes={
"secretapi"
}
},
new Client()
{
//客戶端Id
ClientId="apiClientPassword",
//客戶端密碼
ClientSecrets={new Secret("apiSecret".Sha256()) },
//客戶端授權類型,ResourceOwnerPassword:用戶名密碼模式
AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,
//允許訪問的資源
AllowedScopes={
"secretapi"
}
}
,
new Client()
{
//客戶端Id
ClientId="apiClientImpl",
ClientName="ApiClient for Implicit",
//客戶端授權類型,Implicit:隱藏模式
AllowedGrantTypes=GrantTypes.Implicit,
//允許登錄后重定向的地址列表,可以有多個
RedirectUris = {"https://localhost:5002/auth.html" },
//允許訪問的資源
AllowedScopes={
"secretapi"
},
//允許將token通過瀏覽器傳遞
AllowAccessTokensViaBrowser=true
}
};
}
2,添加IdentityServer的ui模板。
微軟為IdentityServer4創建了一系列的模板,可以在命令行中使用dotnet new -i IdentityServer4.Templates安裝。然后在IdentityServer項目根據目錄下打開命令行,運行dotnet new is4ui 安裝IdentityServer的ui模板。會自動添加Quickstart、wwwroot、Views三個文件夾到此目錄

添加好ui模板后,還需要啟用IdentityServer項目的mvc功能。修改IdentityServer.Startup.ConfigureServices,添加一行代碼
services.AddMvc();
修改IdentityServer.Startup.Configure,添加二行代碼
//訪問wwwroot目錄靜態文件
app.UseStaticFiles();
//使用Mvc中間件
app.UseMvcWithDefaultRoute();
二,Mvc客戶端配置
添加跳傳頁面
在第一步的客戶端實例化中配置了RedirectUris = {"https://localhost:5002/auth.html" },這是一個跳轉頁面,用戶在IdentityServer上登錄成功后將會帶着access_token自動跳轉到這個頁面。現在這個頁面還沒有創建。
在IdentityMvc項目的wwwroot目錄下創建一個名為auth的html頁面。用於redirect_uri。如果uri瞄點中帶有token,把token顯示在頁面上。
IdentityMvc/wwwroot/auth.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var token = null;
window.onload = function () {
var url = window.location.href;
var array = url.split("#");
if (array.length > 1) {
token = array[1];
document.getElementById("content").innerHTML = token;
}
}
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
三,獲取access_token
根據OAuth2.0協議,隱藏模式需要傳的參數如下所示。
client_id:客戶端Id redirect_uri=重定向Url,用戶登錄成功后跳回此地址 response_type=token,固定值,表示獲取token scope=secretapi,此token需要訪問的api
接受參數的地址則是IdentityServer的Discover文檔中的authorization_endpoint節點。把參數和地址拼接成以下地址:http://localhost:5000/connect/authorize?client_id=apiClientImpl&redirect_uri=https://localhost:5002/auth.html&response_type=token&scope=secretapi,直接訪問,會跳轉到用戶登錄頁面

使用之前添加的用戶:apiUser登錄,確認授權訪問secretapi這個api資源

確認后,瀏覽器將會自動跳轉到redirect_url,也就是我們第一步建立的html頁面。

發現token已經被打印出來了。使用這個token用於Bearer授權驗證就可以訪問標識為secretapi的api資源。訪問一下之前的測試接口。

隱藏模式解決了客戶端模式用戶身份驗證和授權的問題,也解決了密碼模式面臨的用戶密碼暴露的問題,適應於全前端沒有后端的第三方應用。但由於token攜帶在url中,安全性方面不能保證。下一篇講的授權碼模式在安全性方面做得更好。
