IdentityServer4(客戶端受權模式)

1.新建三個項目api

   IdentityServer:端口5000  服務器

   IdentityAPI:端口5001app

   IdentityClient:async

2.在IdentityServer項目中添加IdentityServer4的包:Install-Package IdentityServer4ui

   添加一個類:spa

        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("api", "myapi")//定義資源名稱
            };
        }


        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientId = "client",//客戶端獲取token時指定的ClientId值
                    AllowedGrantTypes = GrantTypes.ClientCredentials,//受權模式

                    ClientSecrets = 
                    {
                        new Secret("secret".Sha256())//客戶端獲取token時指定的Secret值
                    },
                    AllowedScopes = { "api" }//設置可訪問的資源名稱
                }
            };
        }

而後在該項目的Startup中注入:3d

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            //注入到容器中
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetApiResources())//加載配置信息
                .AddInMemoryClients(Config.GetClients());
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIdentityServer();//管道
        }
    }

而後你能夠訪問http://localhost:5000/.well-known/openid-configuration code

 

 

3.在IdentityAPI項目中添加一個控制器:控制器頭要添加[Authorize]orm

   添加身份驗證中間件:① 驗證傳入令牌以確保它來自可信發行者,② 令牌驗證是有效的,用於在這個API中間件

    Microsoft.AspNetCore.Authentication.JwtBearer

  在該項目的Startup文件中

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                .AddAuthorization()
                .AddJsonFormatters();

            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>  //使用IdentityServer做爲受權模式
                {
                    options.Authority = "http://localhost:5000";//服務地址
                    options.RequireHttpsMetadata = false;

                    options.ApiName = "api";//訪問的資源名稱
                });
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseAuthentication();
            app.UseMvc();
        }
    }

 

4.IdentityClient項目中添加IdentityModel 庫 

   IdentityModel 包含了一個用於發現端點的客戶端庫。這樣一來你只須要知道 IdentityServer 的基礎地址,實際的端點地址能夠從元數據中讀取。

 

        private static async Task MainAsync()
        {
            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            // request token
            var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api");

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

            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");

            // call api
            var client = new HttpClient();
            client.SetBearerToken(tokenResponse.AccessToken);

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

 

客戶端受權模式一般用於服務器到服務器通訊

相關文章
相關標籤/搜索