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


一、客戶端模式介紹

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

請求步驟為:

  • 客戶端向認證服務器進行認證,並請求一個訪問令牌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();
        }
  • 啟動項

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

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

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

  • 使用postman獲取token

    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,請求成功。


免責聲明!

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



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