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

 

一、首先新建一個webAPI項目作爲IdentityServer的服務端,提供生成Token的服務,首先修改Startup.cs文件,以下圖:web

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

三、在Startup.cs文件中配置作初始化:ide

四、好了,咱們把網站啓動,而後咱們訪問http://localhost:5000/.well-known/openid-configuration(http://localhost:5000是個人程序啓動地址,能夠在Program.cs文件中本身配置。.well-known/openid-configuration是程序的默認配置地址)而後返回以下內容,代表咱們服務端已經沒有什麼問題了。網站

 

五、而後咱們再單首創建一個Webapi項目來實現調用IdentityServer端獲取token實現資源的正常訪問.首先設置啓動地址:spa

六、設置API控制器受權特性:code

 

七、設置啓動配置選項:blog

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

 

九、經過訪問IdentityServer提供的endpoint(步驟4圖中有標記)地址來獲取token,以下圖:資源

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

 

 

附上經過第三方程序來調用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!");
        }
    }
}
相關文章
相關標籤/搜索