9-客户端集成IdentityServer

1-创建客户端的webapi项目

E:\coding\netcore\IdentityServerSample>dotnet new webapi --name IdentityCredentialApi

2-在需要启用授权的方法上增加Authorize标签

3-使用nuget工具安装  IdentityServer4.AccessTokenValidation

4-启用客户端授权, 需要配置连接的授权的服务器等

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options=>{
                options.Authority="http://localhost:5000";
                options.RequireHttpsMetadata=false;
                options.ApiName="api";

            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
           app.UseAuthentication(); //新加
           app.UseMvc();
        }

5-修改启动的url, 为了在测试时与服务器的不冲突, 在Program.cs修改

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>().UseUrls("http://localhost:5001");

6-进行测试,启用服务端和客户端,

如果默认访问需要授权的网页,会报401未授权错误

要想获得授权,第一步通过服务器获得token, http://localhost:5000/connect/token

                        参数 client_id:client client_secret:secret grant_type:client_credentials

第二步,通过返回的token再调用客户端的http://localhost:5001/api/values 地址

 

猜你喜欢

转载自www.cnblogs.com/qinzb/p/9461520.html