微服務(入門四):identityServer的簡單使用(客戶端授權+密碼授權)


IdentityServer簡介(摘自Identity官網)

IdentityServer是將符合規范的OpenID Connect和OAuth 2.0端點添加到任意ASP.NET核心應用程序的中間件,通常,您構建(或重新使用)一個包含登錄和注銷頁面的應用程序(可能還包括同意,具體取決於您的需要),IdentityServer中間件向其添加必要的協議頭,以便客戶端應用程序可以使用這些標准協議與之對話。

托管應用程序可以像您希望的那樣復雜,但我們通常建議通過只包含與身份驗證相關的UI來盡可能地保持攻擊面小。

 

 client               :客戶端,從identityServer請求令牌,用戶對用戶身份校驗,客戶端必須先從identityServer中注冊,然后才能請求令牌。

 sources           :每個資源都有自己唯一的名稱,就是文中所定義的api1服務名稱,indentity會驗證判定是否有訪問該資源的權限。

 access Token  :訪問令牌,由identityServer服務器簽發的,客戶端使用該令牌進行訪問擁有權限的api

 

 

OAuth 2.0四種授權模式(GrantType)

  •  客戶端模式(client_credentials)
  •  密碼模式(password)
  •  授權碼模式(authorization_code)
  •  簡化模式(implicit)

作用

  • 單點登錄

        在多個應用程序當中進行統一登錄或者注銷。

  • api訪問控制
    • 為各種類型的客戶端(如服務器到服務器、Web應用程序、SPA和本機/移動應用程序)頒發API訪問令牌。
  • 聯盟網關

          支持外部身份提供商,如Azure Active Directory、Google、Facebook等。這將使您的應用程序不了解如何連接到這些外部提供商的詳細信息。

開發准備

   開發環境             :vs2019 

   identityServer4:2.4.0

  netcore版本       :2.1

客戶端授權模式介紹

客戶端模式的話是屬於identityServer保護API的最基礎的方案,我們定義個indentityServer服務以及一個需要保護的API服務,

當客戶端直接訪問api的話,由於我們的api服務添加了authorization認證,所以必須要到identityServer放服務器上拿到訪問令牌,客戶端憑借該令牌去對應api服務當中獲取想要得到的數據

添加IdentityServer項目

  1.首先添加新項目,創建ASP.NET Core Web 應用程序  創建一個名稱為identityServer4test的項目,選擇項目類型API  項目進行創建。

 

2.從程序包管理器控制台或者ngGet下載IdentityServer4

  2.1 程序包管理器控制台:install-package IdentityServer4

  2.2 NuGet 的話在對應的程序集,選擇nuget輸入IdentityServer4選擇對應的版本進行下載安裝

  

 

 

3.添加Identity Server4 配置

   資源定義可以通過多種方式實現,具體的請查閱官方api文檔:https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html

 注:1.ApiResource("api1","My Api"),其中api1代表你的唯一資源名稱,在 AllowedScopes = { "api1" }當中必須配置上才可以進行訪問

 

using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace IdentityServer4Test.IndntityConfig
{
    public class IdentityServerConfig
    {
        /// <summary>
        /// 添加api資源
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetResources()
        {
            return new List<ApiResource>
            {
         
new ApiResource("api1","My Api") }; } /// <summary> /// 添加客戶端,定義一個可以訪問此api的客戶端 /// </summary> /// <returns></returns> public static IEnumerable<Client> GetClients() { return new List<Client> { new Client { /// ClientId = "client", // 沒有交互性用戶,使用 客戶端模式 進行身份驗證。 AllowedGrantTypes = GrantTypes.ClientCredentials, // 用於認證的密碼 ClientSecrets = { new Secret("123454".Sha256()) }, // 客戶端有權訪問的范圍(Scopes) AllowedScopes = { "api1" } } }; } } }

 

4.在startUp當中注入IdentityServer4 服務

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Test;
using IdentityServer4Test.IndntityConfig;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace IdentityServer4Test
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            // 在DI容器中注入identityServer服務
            services.AddIdentityServer()
         
        .AddInMemoryApiResources(IdentityServerConfig.GetResources())//添加配置的api資源
        .AddInMemoryClients(IdentityServerConfig.GetClients())//添加客戶端,定義一個可以訪問此api的客戶端
            .AddDeveloperSigningCredential();
            

        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //添加identityserver中間件到http管道
            app.UseIdentityServer();
            //app.UseMvc();
        }
    }
}

5.此時啟動程序輸入 http://localhost:3322/.well-known/openid-configuration可以得到如下網站,這是identity Server4 提供的配置文檔

6.用postMan請求獲取access_token

  

標注:body 當中的參數

        grant_type    :對應api AllowedGrantTypes 類型表示授權模式

        client_id        : 對應clentID 

        client_secret: 客戶端秘鑰

       

7.拿到token以后就可以根據token去訪問我們的服務程序,服務程序,首先也是創建一個webApi程序,並且從NuGet下載所需的依賴

  •    IdentityServer4.AccessTokenValidation(程序報管理器的話加上install-package IdentityServer4.AccessTokenValidation)

  7.1 配置authentication,並且添加    app.UseAuthentication();到http管道當中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace IndentityServerClientTest
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
             //注入authentication服務
            services.AddAuthentication("Bearer")
            
               .AddIdentityServerAuthentication(options =>
               {
                   options.Authority = "http://localhost:3322";//IdentityServer服務地址
                   options.ApiName = "api1"; //服務的名稱,對應Identity Server當中的Api資源名稱,如果客戶端得到的token可以訪問此api的權限才可以訪問,否則會報401錯誤
                   options.RequireHttpsMetadata = false;
               });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //添加authentication中間件到http管道
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}

7.2 引用Microsoft.AspNetCore.Authorization;命名空間,添加authorize認證

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace IndentityServerClientTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }

        // DELETE api/values/5
        [Route("send")]
        [HttpGet]
        public string send()
        {
            return "成功了";

        }

    }
}

7.3. 直接訪問的話會報401錯誤

 

7.4 在請求頭當中添加Authorization 參數,參數值為Bearer加上空格 加上咱們剛才獲取到的access_token 請求成功!~~

 密碼授權                                                         

  

官方介紹

 OAuth2.0資源所有者密碼授權允許客戶端向令牌服務發送用戶名和密碼,並獲取代表該用戶的訪問令牌。

 除了不能承載瀏覽器的遺留應用程序之外,規范通常建議不要使用資源所有者密碼授予。一般來說,當您想要對用戶進行身份驗證並請求訪問令牌時,最好使用交互式OpenID連接流之一。

 然而,這種授權類型允許我們將用戶的概念引入到QuickStartIdentityServer,這就是我們展示它的原因。

 1.配置可訪問的用戶信息以及授權模式

   新添加一個client模式並且更改AllowedGrantTypes 類型為“GrantTypes.ResourceOwnerPassword” 

 

 

using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace IdentityServer4Test.IndntityConfig
{
    public class IdentityServerConfig
    {
        /// <summary>
        /// 添加api資源
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("api1","My Api")
            };
        }
        /// <summary>
        /// 添加客戶端,定義一個可以訪問此api的客戶端
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
                {
                    new Client
                    {
                        ///
                        ClientId = "client",

                        // 沒有交互性用戶,使用 客戶端模式 進行身份驗證。
                        AllowedGrantTypes = GrantTypes.ClientCredentials,
                       
                        // 用於認證的密碼
                        ClientSecrets =
                        {
                            new Secret("123454".Sha256())
                        },
                        // 客戶端有權訪問的范圍(Scopes)
                        AllowedScopes = { "api1" }
                    }
                    ,
                    new Client
                    {
                        ClientId = "client1",


                        AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                       
                        // 用於認證的密碼
                        ClientSecrets =
                        {
                            new Secret("laozheng".Sha256())
                        },
                        RequireClientSecret=false,
                        // 客戶端有權訪問的范圍(Scopes)
                        AllowedScopes = { "api1" }
                    }
                };

        }

        public static List<TestUser> GetTestUsers()
        {
            return new List<TestUser> {
                new TestUser{
                    SubjectId="1",
                    Password="111",
                    Username="111",
                }
            };
        }
    }
}

1.1 修改startup.cs文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Test;
using IdentityServer4Test.IndntityConfig;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace IdentityServer4Test
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            // 在DI容器中注入identityServer服務
            services.AddIdentityServer()
         
        .AddInMemoryApiResources(IdentityServerConfig.GetResources())
        .AddInMemoryClients(IdentityServerConfig.GetClients())
        .AddTestUsers(IdentityServerConfig.GetTestUsers())
            .AddDeveloperSigningCredential();
            

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //添加identityserver中間件到http管道
            app.UseIdentityServer();
            //app.UseMvc();
        }
    }
}

 

2.獲取token

 

 

3.通過剛才獲取到的token訪問接口

 

 

 

 

 

快速入口:微服務(入門一):netcore安裝部署consul

快速入口: 微服務(入門二):netcore通過consul注冊服務

快速入口: 微服務(入門三):netcore ocelot api網關結合consul服務發現

快速入口:微服務(入門四):identityServer的簡單使用(客戶端授權) 


免責聲明!

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



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