使用IdentityServer4實現一個簡單的Oauth2客戶端模式授權


 

1、首先新建一個webAPI項目做為IdentityServer的服務端,提供生成Token的服務,首先修改Startup.cs文件,如下圖:

2、增加一個Config.cs文件,以便於提供資源和認證設置,如下圖:

3、在Startup.cs文件中配置做初始化:

4、好了,我們把網站啟動,然后我們訪問http://localhost:5000/.well-known/openid-configuration(http://localhost:5000是我的程序啟動地址,可以在Program.cs文件中自己配置。.well-known/openid-configuration是程序的默認配置地址)然后返回如下內容,表明我們服務端已經沒有什么問題了。

 

5、然后我們再單獨創建一個Webapi項目來實現調用IdentityServer端獲取token實現資源的正常訪問.首先設置啟動地址:

6、設置API控制器授權特性:

 

7、設置啟動配置選項:

8.我們先在Postman中用一個錯誤的token去訪問,結果提示未授權。

 

9、通過訪問IdentityServer提供的endpoint(步驟4圖中有標記)地址來獲取token,如下圖:

10.通過獲取的token,去訪問被限制的資源(即步驟6圖中標識的位置),返回成功,即訪問成功:

 

 

附上通過第三方程序來調用token,然后攜帶token訪問API的demo:

using System;
using System.Net.Http;
using IdentityModel.Client;
namespace identityServerClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var discoveryClient=DiscoveryClient.GetAsync("http://localhost:5000").Result;
            if(discoveryClient.IsError)
            {
                Console.WriteLine("there are some errors");
            }
            var tokenClient=new TokenClient(discoveryClient.TokenEndpoint,"client","secret");
            var tokenResponse=tokenClient.RequestClientCredentialsAsync("api").Result;
            if(tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
            }
            else
            {
                Console.WriteLine(tokenResponse.Json);
            }
            var httpClient=new HttpClient();
            httpClient.SetBearerToken(tokenResponse.AccessToken);
            var response=httpClient.GetAsync("http://localhost:5001/api/values").Result;
            if(response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }
            Console.ReadLine();


            Console.WriteLine("Hello World!");
        }
    }
}

 


免責聲明!

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



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