ASP.NET Core3.1使用IdentityServer4中間件系列隨筆(三):創建使用[ClientCredentials客戶端憑證]授權模式的客戶端


配套源碼:https://gitee.com/jardeng/IdentitySolution

 

上一篇《ASP.NET Core3.1使用IdentityServer4中間件系列隨筆(二):創建API項目,配置IdentityServer保護API資源》創建了受保護的API資源項目

並通過Postman獲取到了access_token,再使用access_token去訪問受保護的API資源,本篇將創建一個使用[ClientCredentials-客戶端憑證]授權模式的客戶端,來對受保護的API資源進行訪問。

先了解一下客戶端憑證模式

Client Credentials:客戶端憑證模式;該方法通常用於服務器之間的通訊;該模式僅發生在Client與Identity Server之間。
該模式的適用場景為服務器與服務器之間的通信。
比如對於一個電子商務網站,將訂單和物流系統分拆為兩個服務分別部署。
訂單系統需要訪問物流系統進行物流信息的跟蹤,物流系統需要訪問訂單系統的快遞單號信息進行物流信息的定時刷新。
而這兩個系統之間服務的授權就可以通過這種模式來實現。

1、創建一個名為 ClientCredentialsConsoleApp 控制台應用。

 

 

 

 

 

 2、添加nuget包:IdentityModel

 

 

 3、在Program.cs類中編寫代碼

using System;
using System.Net.Http;
using System.Threading.Tasks;

using IdentityModel.Client;

using Newtonsoft.Json.Linq;

namespace ClientCredentialsConsoleApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            //discovery endpoint - 發現終結點
            HttpClient client = new HttpClient();
            DiscoveryDocumentResponse disco =
                await client.GetDiscoveryDocumentAsync("http://localhost:5000");
            if (disco.IsError)
            {
                Console.WriteLine($"[DiscoveryDocumentResponse Error]: {disco.Error}");
                return;
            }

            //request access token - 請求訪問令牌
            TokenResponse tokenResponse = await client.RequestClientCredentialsTokenAsync(
                new ClientCredentialsTokenRequest
                {
                    Address = disco.TokenEndpoint,
                    ClientId = "client",
                    ClientSecret = "secret",
                    Scope = "api1"
                });
            if (tokenResponse.IsError)
            {
                Console.WriteLine($"[TokenResponse Error]: {tokenResponse.Error}");
                return;
            }
            else
            {
                Console.WriteLine($"Access Token: {tokenResponse.AccessToken}");
            }

            //call API Resource - 訪問API資源
            HttpClient apiClient = new HttpClient();
            apiClient.SetBearerToken(tokenResponse.AccessToken);
            HttpResponseMessage response = await apiClient.GetAsync("http://localhost:6000/weatherforecast");
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine($"API Request Error, StatusCode is : {response.StatusCode}");
            }
            else
            {
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(JArray.Parse(content));
            }

            Console.ReadKey();
        }
    }
}

4、先將IdentityServer授權服務器、API項目運行起來,再運行控制台項目。

創建了兩個批命令,用於快速啟動項目

 

 

 

> IdentityServer

cd IdentityServer/bin/Debug/netcoreapp3.1
dotnet IdentityServer.dll --urls "http://*:5000"

> WebApplication1

cd WebApplication1/bin/Debug/netcoreapp3.1
dotnet WebApplication1.dll --urls "http://*:6000"

運行結果:

 

 可以看到,成功獲取到AccessToken,並使用AccessToken訪問到受保護的API獲取到結果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM