.Net Core身份認證:IdentityServer4實現OAuth 2.0 客戶端模式

一、客戶端模式介紹

客戶端模式(Client Credentials Grant)是指客戶端直接向認證服務(Authorization Server)發送認證請求,獲取token,進行認證,一般適用于受信任的客戶端。

image.png

請求步驟為:

  • 客戶端向認證服務器進行認證,并請求一個訪問令牌token;
  • 認證服務器進行認證,通過之后,返回客戶端一個訪問令牌。

二、創建認證服務

  • 創建一個認證服務IdentityServerCenter,通過NuGet安裝IdentityServer4;
  • 添加配置資源與客戶端的文件,引入using IdentityServer4.Models
   public class Config
    {
        public static IEnumerable<ApiResource> GetResources()
        {
            return new List<ApiResource> {
                    new ApiResource {
                        Name = "ImageResource",
                        Scopes={ new Scope ("ImageResource")},//Scopes必須配置,否則獲取token時返回 invalid_scope
                    },
                    new ApiResource { Name = "FileResourse" },
                    new ApiResource { Name="Api",    Scopes={new Scope ("Api") } }
                };
        }
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client> {
                    new Client {
                        ClientId = "ClientId",
                        AllowedGrantTypes =GrantTypes.ClientCredentials,//授權模式:客戶端模式
                        AllowedScopes={ "ImageResource","Api" }, //允許訪問的資源 GetResources()中配置的
                       ClientSecrets={ new Secret { Value= "ClientSecret".Sha256(), Expiration=DateTime.Now.AddMinutes(5)} }
                    } };
        }
    }
  • 注入IdentityServer4,添加IdentityServer4配置
        public void ConfigureServices(IServiceCollection services)
        {
            //注入IdentityServer   添加IdentityServer4配置
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetResources()) //添加配置的資源ApiResource
                .AddInMemoryClients(Config.GetClients());//添加配置的客戶端Client
          //  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
  • 使用IdentityServer4
     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //使用IdentityServer
            app.UseIdentityServer();
        }
  • 啟動項
    image.png

    由于未使用MVC,訪問該api返回404。IdentityServer4提供一個地址可獲取相關配置項。
http://examplehostname.com.well-known/openid-configuration/

訪問 http://localhost:5000/.well-known/openid-configuration 將返回的信息序列化如下

image.png

scopes_supported": ["ImageResource", "Api", "offline_access"]即為Config中配置的訪問的資源AllowedScopes

  • 使用postman獲取token
    image.png

    grant_type為客戶端授權client_credentials,client_idClient_SecretConfig中配置的ClientIdSecret。接下來創建一個可訪問的資源。

三、創建資源服務

  • 創建一個資源服務項目ImageResourceApi
  • 注入認證
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(config => {
                config.DefaultScheme = "Bearer"; 
            }).AddIdentityServerAuthentication(option=> {
                option.ApiName = "ImageResource"; 
                option.Authority = "http://localhost:5000"; //認證服務的url
                option.ApiSecret = "ClientSecret".ToSha256();// 訪問的secret
                option.RequireHttpsMetadata = false;
                
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            //使用認證
            app.UseAuthentication();
            app.UseMvc();
        }
        
  • 啟動資源服務,返回401未授權;
  • 使用postman帶著token請求資源服務ImageResourceApi,請求成功。
    image.png
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,868評論 18 139
  • 以下思路參考于 IdentityServer4 源碼,流程。閱讀文章請 先 熟悉 OAuth 2.0, Open ...
    JacoChan閱讀 1,427評論 0 5
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,522評論 1 92
  • OAuth是一個關于授權(authorization)的開放網絡標準,在全世界得到廣泛應用,目前的版本是2.0版。...
    常曉曉閱讀 782評論 0 0
  • 世間安得雙全法 不負如來不負卿 又有誰知 表面的無情背后卻是最大的有情 菩提薩埵 世間何事能大過生死 百年后誰又認...
    元子慧寂閱讀 285評論 0 3