<二>客户端集成identityserver4

1、新建一个api项目来作为客户端叫ClientCredentialsApiDemo

 2、clientApi项目中配置identityserver4相关授权

1、引用IdentityServer4.AccessTokenValidation
2、controller添加[Authorize]特性
3、startup的ConfigureServices方法中添加相关代码
 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(option =>
                {
                    option.Authority = "http://localhost:5000";    //认证地址
                    option.RequireHttpsMetadata = false;           
                    option.ApiName = "api";                        //访问api名称
                });
                
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseAuthentication();//启用授权
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
  [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }
        [HttpGet]

        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

3、启动客户端并绑定5001端口,用postman访问5001端口中的get方法,出现未授权

4、上一节我们用postman 拿过token,那么我们同样的方式去拿一次。

在访问5001端口api的时候加进去授权信息。

 

 5、成功拿到数据没说明基于ClientCredentials的授权添加成功!

原文地址:https://www.cnblogs.com/choii/p/13763285.html