(精华)2020年11月21日 .NET Core 使用IdentityServer4的Client Credentials模式访问保护API

一:Client Credentials介绍

Client Credentials:客户端凭证模式;该方法通常用于服务器之间的通讯;该模式仅发生在Client与Identity Server之间。
该模式的适用场景为服务器与服务器之间的通信
1:添加nuget包:IdentityModel
2:使用如下代码访问api

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();
        }
    }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页