1.新建项目并添加引用
新建一个asp .net core 2.0的项目
引用IdentityServer4.AccessTokenValidation
2.配置
将Api与IdentityServer服务器挂钩
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;
//这个Api资源的名称,注意与IdentityServer的Api资源对应
options.ApiName = "api1";
});
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseMvc();
}
}
3.Api接口
添加一个新的Controller,使用此控制器来测试授权要求,以及通过Api可视化声明身份
[Route("identity")]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
网友评论