Identity Server 4 從入門到落地(七)—— 控制台客戶端
- 2021 年 12 月 8 日
- 筆記
- Dot Net, Identity Server, Identity Server 4
前面的部分:
Identity Server 4 從入門到落地(一)—— 從IdentityServer4.Admin開始
Identity Server 4 從入門到落地(二)—— 理解授權碼模式
Identity Server 4 從入門到落地(三)—— 創建Web客戶端
Identity Server 4 從入門到落地(四)—— 創建Web Api
Identity Server 4 從入門到落地(五)—— 使用Ajax 訪問 Web Api
Identity Server 4 從入門到落地(六)—— 簡單的單頁面客戶端
認證服務和管理的github地址: //github.com/zhenl/IDS4Admin
客戶端及web api示例代碼的github地址://github.com/zhenl/IDS4ClientDemo
前面我們試驗的客戶端都是有最終用戶參與的,也就是需要用戶登錄進行認證。如果項目中存在後台服務訪問Web Api,這種情況下沒有用戶參與認證過程,就需要使用Client Credentials flow。我們創建一個簡單的控制台項目試驗一下。
首先在認證服務的管理應用中創建一個新的客戶端,選擇使用Client Credentials flow:
然後設置作用域和客戶端密鑰,這裡作用域中添加myapi,訪問我們的測試Api:
在我們前面的測試解決方案中增加一個新的.Net 6控制台項目,名稱為IDSClientConsole,創建完成後,引入程序包IdentityModel:
修改Program.cs如下:
using IdentityModel.Client;
using Newtonsoft.Json.Linq;
await GetTokenAndCallApiAsync();
static async Task GetTokenAndCallApiAsync()
{
// discover endpoints from metadata
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("//localhost:4010");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "consoleclient",
ClientSecret = "secret1",
Scope = "myapi"
});
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);
// call api
var apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);
var response = await apiClient.GetAsync("//localhost:5153/WeatherForecast");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
}
}
設置解決方案的啟動項目,將這個控台項目和Web Api設置為同時啟動:
項目啟動後,控制台應用通過認證,然後訪問Web Api獲取數據,結果如下:
到這裡,我們已經試驗了在Web應用、單頁面應用和客戶端應用中訪問認證服務進行認證,還測試了認證服務對Web Api的保護,接下來準備落地,為在項目中實際使用做準備,還有如下問題需要解決:
- 基於.Net Framework的遺留項目如何使用認證服務。
- 現有的使用Asp.Net Core使用Identity的項目如何改造。
- 簡化客戶端和Web Api的編程,將代碼中寫死的配置項移動到配置文件。
- 認證服務和管理應用的多種部署方式:部署到IIS,部署到Docker容器等等。
接下來的部分我們將一一解決這些問題。