【WebAPI No.3】API的訪問控制IdentityServer4


介紹:

IdentityServer是一個OpenID Connect提供者 - 它實現了OpenID Connect和OAuth 2.0協議。是一種向客戶發放安全令牌的軟件。

官網給出的功能解釋是:

  • 保護您的資源
  • 使用本地帳戶存儲或通過外部身份提供商對用戶進行身份驗證
  • 提供會話管理和單點登錄
  • 管理和認證客戶
  • 向客戶發布身份和訪問令牌
  • 驗證令牌

IdentityServe4的四種模式:

  • 授權碼模式(authorization code)
  • 簡化模式(implicit)
  • 密碼模式(resource owner password credentials)
  • 客戶端模式(client credentials)

以下是IdentityServer的一個大致流程圖:

 

注冊IdentityServe4認證服務器:

先在asp.net core我們選中空模版。因為本身寫的業務也不多,只是為了做token的認證處理,所有建這個做測試比較方便。

創建代碼示例:

什么時候都不要忘記添加引用哦:

NuGet命令行:Install-Package IdentityServer4

當然你也可以這樣:

然后創建config.cs類來處理我們的一些業務:

 //定義范圍
        #region 定義要保護的資源(webapi)
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("FirstAPI", "API接口安全測試")
            };
        }
        #endregion

        #region 定義可訪問客戶端
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    //客戶端id自定義
                    ClientId = "YbfTest",

                    AllowedGrantTypes = GrantTypes.ClientCredentials, ////設置模式,客戶端模式

                    // 加密驗證
                    ClientSecrets = new List<Secret>
                    {
                        new Secret("secret".Sha256())
                    },

                    // client可以訪問的范圍,在GetScopes方法定義的名字。
                    AllowedScopes = new List<string>
                    {
                        "FirstAPI"
                    }
                }
            };
        } 
        #endregion
View Code

以上就是一個基本的處理類了。然后我們開始在Startup.cs 配置IdentityServer4

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
                 .AddDeveloperSigningCredential()
                 .AddInMemoryApiResources(Config.GetApiResources())  //配置資源               
                 .AddInMemoryClients(Config.GetClients());//配置客戶端
        }
View Code
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //將IddiTyServer添加到管道中。
            app.UseIdentityServer();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
View Code

這樣就可以啟動項目了,確認項目啟動完成后,還要確認服務是否開啟成功:在地址后增加地址:/.well-known/openid-configuration 例如:

出現以上結果就是啟動成功了。

當然你也可以使用postMan測試工具測試:

需要輸入

  • grant_type為客戶端授權client_credentials,
  • client_idConfig中配置的ClientId
  • Client_Secret為Config中配置的Secret

例如:

 創建webAPI資源服務器

這個比較簡單了,首先創建一個簡單的webapi程序即可。

還是老規矩咯iuput,什么時候都不要忘記引用:

通過nuget添加即可:IdentityServer4.AccessTokenValidation

然后點擊確定安裝就可以了。

主要認證注冊服務:

在Startup類里面的ConfigureServices方法里面添加注冊

        public void ConfigureServices(IServiceCollection services)
        {
            //注冊IdentityServer 
            services.AddAuthentication(config => {
                config.DefaultScheme = "Bearer"; //這個是access_token的類型,獲取access_token的時候返回參數中的token_type一致
            }).AddIdentityServerAuthentication(option => {
                option.ApiName = "FirstAPI"; //資源名稱,認證服務注冊的資源列表名稱一致,
                option.Authority = "http://127.0.0.1:5000"; //認證服務的url
                option.RequireHttpsMetadata = false; //是否啟用https

            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

然后在在Startup的Configure方法里配置Authentication中間件:

           //配置Authentication中間件
            app.UseAuthentication();

然后添加一個控制器進行驗證測試:

我這里寫了一個獲取value值簡單檢測一下。

 // GET api/values
        [HttpGet]
        [Authorize]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

這里注意要添加[Authorize]特性。用來做驗證是否有權限的。沒有的話,以上做的沒有意義。需要引用命名空間:using Microsoft.AspNetCore.Authorization;

看一下正確的請求結果:

如果不傳token值請求:

 

 

注意這里就會返回401的未授權狀態。 

創建Client(客戶端)

上面我們使用的是postman請求的以演示程序是否創建成功,這里我們假設一個用戶的使用客戶端,這里我們創建一個控制台來模擬一下真實的小場景。

既然是控制台就沒什么好說的直接上代碼main函數:

Task.Run(async () =>
            {
                //從元數據中發現終結點,查找IdentityServer
                var disco = await DiscoveryClient.GetAsync("http://127.0.0.1:5000");
                if (disco.IsError)
                {
                    Console.WriteLine(disco.Error);
                    return;
                }

                //向IdentityServer請求令牌
                var tokenClient = new TokenClient(disco.TokenEndpoint, "YbfTest", "YbfTest123");//請求的客戶資源
                var tokenResponse = await tokenClient.RequestClientCredentialsAsync("FirstAPI");//運行的范圍

                if (tokenResponse.IsError)
                {
                    Console.WriteLine(tokenResponse.Error);
                    return;
                }

                Console.WriteLine(tokenResponse.Json);

                //訪問Api
                var client = new HttpClient();
                //把令牌添加進請求
                //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",tokenResponse.AccessToken);
                //client.SetBearerToken(tokenResponse.AccessToken);
                client.SetToken("Bearer", tokenResponse.AccessToken);

                var response = await client.GetAsync("http://localhost:42033/api/values");
                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine(response.StatusCode);
                }
                else
                {
                    var content = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(JArray.Parse(content));
                }
            });

            Console.ReadLine();
View Code

這里主要介紹一下請求資源時添加令牌主要有三種形式,我都在代碼給出,根據api資源的注冊形式選擇適合的。api的注冊我也寫了兩種形式。主要的區別就是token前面的Bearer,如果想寫成自定義的和默認成Bearer就是這里的區分。

自定義就要使用:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",tokenResponse.AccessToken);

如果全局默認的形式就不比每次請求都要添加所以可以寫成:

client.SetBearerToken(tokenResponse.AccessToken);

運行項目之后出現成功界面:

 

 傳送門

WebApi系列文章目錄介紹


免責聲明!

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



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