IdentiyServer Client Credentials (Api Resources Protected)

Crime tools: VS2019 Postman

Weather: Cloudy

1. Create another api project for testing client_credentials

Install package Microsoft.AspNetCore.Authentication.JwtBearer

2. Add Authentication server and policy to validate access_token

  public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();

           services.AddAuthentication("Bearer")
          .AddJwtBearer("Bearer", options =>
          {
              options.Authority = "http://localhost:56054";

              options.RequireHttpsMetadata = false;
              options.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateAudience = false
              };
          });

           services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiScope", policy =>
                {
                    policy.RequireAuthenticatedUser();
                    policy.RequireClaim("scope", "message_service");
                });
           });
        }

3. Using policy to validate access_token scopes

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

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

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

4. Add Authorize attribute to protect api

 [Authorize]
    public class ValuesController : ControllerBase
    {
        // GET: api/<ValuesController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

 

posted @ 2021-05-27 22:13  Kevin-xk  阅读(76)  评论(0)    收藏  举报