より多くのAPIエンドポイントを追加する¶
IdentityServer4をホスティングするアプリケーションに、より多くのAPIエンドポイントを追加できます。
通常、これらのAPIは、ホストされているIdentityServerのインスタンスによって保護されます。これは問題ではありません。トークン検証ハンドラをホストに追加するだけです(ここを参照)。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// details omitted
services.AddIdentityServer();
services.AddAuthentication()
.AddIdentityServerAuthentication("token", isAuth =>
{
isAuth.Authority = "base_address_of_identityserver";
isAuth.ApiName = "name_of_api";
});
}
APIでは、[Authorize]属性を追加して、使用する認証方式を明示的に参照する必要があります(tokenこの例では、任意の名前を自由に選択できます)。
public class TestController : ControllerBase
{
[Route("test")]
[Authorize(AuthenticationSchemes = "token")]
public IActionResult Get()
{
var claims = User.Claims.Select(c => new { c.Type, c.Value }).ToArray();
return Ok(new { message = "Hello API", claims });
}
}
ブラウザからそのAPIを呼び出す場合は、さらにCORSを設定する必要があります(こちらを参照)。
発見¶
また、エンドポイントを検出文書に追加することもできます(例
services.AddIdentityServer(options =>
{
options.Discovery.CustomEntries.Add("custom_endpoint", "~/api/custom");
})