認證受權:IdentityServer4

前言

  上一篇文章<學習OIDC>介紹了OIDC協議,本篇開始咱們就來具體來學習OIDC的具體實現IdentityServer4 學習。html

1、IdentityServer4 是什麼?

   IdentityServer4是用於ASP.NET Core的OpenID Connect和OAuth 2.0框架。git

  能夠構建(或從新使用)包含登陸和註銷頁面的應用程序,IdentityServer中間件會向其添加必要的協議頭,以便客戶端應用程序能夠使用這些標準協議與其對話。github

   

   能夠在應用程序中使用如下功能:web

    • 身份驗證即服務

      全部應用程序(Web,本機,移動,服務)的集中式登陸邏輯和工做流。IdentityServer是OpenID Connect 的官方認證明現數據庫

    • 單點登陸/退出

      多種應用程序類型的單點登陸(註銷)api

    • API的訪問控制

      爲各類類型的客戶端(例如,服務器到服務器,Web應用程序,SPA和本機/移動應用程序)的API發出訪問令牌瀏覽器

    • 聯合網關

      支持外部身份提供程序,例如Azure Active Directory,Google,Facebook等。這使您的應用程序免受如何鏈接到這些外部提供程序的詳細信息的影響。服務器

2、簡單使用示例

先建立項目目錄結構(以下圖)app

 一、IdentityServer 認證服務實現

  a) 建立一個空的WebApi項目-cz.IdentityServer,並添加IdentityServer4項目引用:以下圖:框架

Install-Package IdentityServer4

  b) 要啓用IdentityServer服務,不只要把 IdentityServer 註冊到容器中, 還須要配置一下內容:

    •  Authorization Server 保護了哪些 API (資源);
    • 哪些客戶端 Client(應用) 能夠使用這個 Authorization Server;

    • 指定能夠使用 Authorization Server 受權的 Users(用戶)

    建立文件 InMemoryConfig.cs,用於設置以上相關內容:    

  View Code

    GetApiResources:這裏指定了name和display name, 之後api使用authorization server的時候, 這個name必定要一致

    GetClients: 認證客戶端列表

    Users: 這裏的內存用戶的類型是TestUser, 只適合學習和測試使用, 實際生產環境中仍是須要使用數據庫來存儲用戶信息的, 例如接下來會使用asp.net core identity. TestUser的SubjectId是惟一標識.

   在Startup.cs中啓用IdentityServer服務

       修改StartUp.cs中的ConfigureServices方法

複製代碼
public void ConfigureServices(IServiceCollection services)
{
            services.AddControllersWithViews();
            services.AddIdentityServer()
              .AddDeveloperSigningCredential()
              .AddInMemoryApiResources(InMemoryConfig.GetApiResources())
              .AddTestUsers(InMemoryConfig.Users().ToList())
              .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResourceResources())
              .AddInMemoryClients(InMemoryConfig.GetClients());
}
複製代碼

    修改StartUp.cs中的Configure方法    

複製代碼
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
       //啓用IdentityServer
            app.UseIdentityServer();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
複製代碼

   運行此項目,打開瀏覽器訪問http://localhost:5600/.well-known/openid-configuration你將會看到IdentityServer的各類元數據信息。

    

  c) 引入QuickStartUI界面

   IdentityServer提供了一套UI以使咱們能快速的開發具備基本功能的認證/受權界面,下載地址:QuickStartUI

   下載後,把QuickStartUI中:wwwroot、Quickstart、Views拷貝到項目中,以下結構:、

   

   修改Statup.cs內容以下:

  View Code

   運行以下效果:

   

 二、IdentityServer 集成Api服務

   a)添加web api項目cz.Api.Order,並添加nuget中安裝IdentityServer4.AccessTokenValidation ,以下圖:  

命令:Install-Package IdentityServer4.AccessTokenValidation

    

 

   b) 修改StartUp.cs文件    

複製代碼
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.AddControllers();

            //IdentityServer
            services.AddMvcCore()
                    .AddAuthorization();

            //配置IdentityServer
            services.AddAuthentication("Bearer")
                        .AddIdentityServerAuthentication(options =>
                        {
                            options.RequireHttpsMetadata = false; //是否須要https
                            options.Authority = $"http://localhost:5600";  //IdentityServer受權路徑
                            options.ApiName = "order";  //須要受權的服務名稱
                        });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
       //啓用Authentication中間件
            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
複製代碼

    c) 對cz.Api.Order項目中WebApi添加[Authorize]特性    

複製代碼
[Route("identity")]
[ApiController]
[Authorize]
 public class IdentityController : ControllerBase
{
}
複製代碼

   d) 此時調用該服務時提示401,以下圖:

    

 

   e) 能夠經過client信息獲取token,而後經過Header傳遞token 調用weapi

  

 

    

3、總結

  經過上面的例子,很簡單就實現了WepApi的認證受權效果;主要步驟以下:

  • 前往IdentityServer服務中,設置須要請求的ApiResource,Client,User內容
  • WebApi服務設置IdentityServerAuthentication地址(對接認證服務)
  • 調用WebApi時,先在IdentityServer中根據設置的方式獲取access token,再帶着access token請求接口才能正常訪問

4、後續

  IdentityServer包含的內容有不少,準備從多個內容來學習記錄使用IdentityServer的功能:SSO(單點登陸)、各類受權模式使用、三方帳號登陸……

  最後來實現一個本身的統一身份認證服務 諾頓教育

相關文章
相關標籤/搜索