1.創(chuàng)建項(xiàng)目并添加引用
創(chuàng)建ASP.NET Core Web API項(xiàng)目IdentityServer.EasyDemo.Api
1
2
引用IdentityServer4.AccessTokenValidation
3
2.定義一個(gè)Api接口
新增接口文件IdentityController.cs抗悍,用于測(cè)試授權(quán)
如果你直接訪問(wèn)http://localhost:5001/identity ,你會(huì)得到一個(gè)401錯(cuò)誤,因?yàn)檎{(diào)用這個(gè)接口需要憑證
這里設(shè)置一個(gè)Api接口纱兑,路由是"identity",跟傳統(tǒng)的/controller/action訪問(wèn)路由不同候齿,GET請(qǐng)求訪問(wèn)/identity即可
[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 });
}
}
3.配置Api
services添加IdentityServerAuthentication,設(shè)置授權(quán)地址為IdentityServer的網(wǎng)址(這里保證了在用戶訪問(wèn)到未授權(quán)的方法時(shí)界拦,會(huì)自動(dòng)跳轉(zhuǎn)到IdentityServer的授權(quán)頁(yè)面)
注意保證Api的ApiName在IdentityServer的Api集合中
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
//將認(rèn)證服務(wù)添加到DI,配置"Bearer"作為默認(rèn)方案
.AddAuthorization()
.AddJsonFormatters();
services.AddAuthentication("Bearer")
//將IdentityServer訪問(wèn)令牌驗(yàn)證處理程序添加到DI中以供身份驗(yàn)證服務(wù)使用
.AddIdentityServerAuthentication(options =>
{
//用于授權(quán)的地址
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
//該Api項(xiàng)目對(duì)應(yīng)的IdentityServer的Api資源,與GetApiResources方法里面的Api名稱對(duì)應(yīng)
options.ApiName = "api1";
});
}
public void Configure(IApplicationBuilder app)
{
//將認(rèn)證中間件添加到流水線中轿腺,以便在對(duì)主機(jī)的每次呼叫時(shí)自動(dòng)執(zhí)行認(rèn)證
app.UseAuthentication();
app.UseMvc();
}
}
4.在屬性中將Api項(xiàng)目的端口號(hào)設(shè)置為5001
4