IdentityServer4学习系列:第一章:Client Credentials

Authentication:身份验证; 认证;鉴定

Authorization:授权

Client Credentials

原理:

 

 

 

客户端认证代码

  public void ConfigureServices(IServiceCollection services)
{                      
     services.AddControllers();
     services.AddAuthentication("Bearer")
    .AddIdentityServerAuthentication(
         options =>
        {
             options.Authority = "http://localhost:5000"; //权限验证url
             options.RequireHttpsMetadata = false;//是否开启https
             options.ApiName = "api";
        });
     //services.AddAuthentication("Bearer")
     //   .AddJwtBearer("Bearer", options =>
     //   {
     //       options.Authority = "http://localhost:5000";
     //       options.RequireHttpsMetadata = false;
     //       options.Audience = "api";
     //   });

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

   app.UseHttpsRedirection();
   app.UseRouting();

   app.UseAuthentication();//认证 必须放在授权前面,否则无效
   app.UseAuthorization();//授权

   app.UseEndpoints(endpoints =>
  {
  endpoints.MapControllers();
  });
}

注意点:app.UseAuthentication()必须放在app.UseAuthorization() (认证必须放在授权的前面)

客户端授权认证代码:

static async Task Main(string[] args)
{
   //Console.WriteLine("Hello World!");
   // 从元数据中发现端口
   // 调用API
   var client = new HttpClient();
   var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
   // 请求以获得令牌

   var tokenResponse = await client.RequestClientCredentialsTokenAsync(
   new ClientCredentialsTokenRequest()
  {
       Address = disco.TokenEndpoint,
       ClientId = "client",
       ClientSecret = "secret",
       Scope = "api"
  });

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

   Console.WriteLine(tokenResponse.Json);

   client.SetBearerToken(tokenResponse.AccessToken);

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

}

 

posted @ 2020-05-30 16:00  勤奋的码农1  阅读(260)  评论(0)    收藏  举报