第43章 添加更多API端点 - Identity Server 4 中文文档(v1.0.0)

您可以向托管IdentityServer4的应用程序添加更多API端点。

您通常希望通过它们所托管的IdentityServer实例来保护这些API。这不是问题。只需将令牌验证处理程序添加到主机(请参阅此处):

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(请参阅此处)。

43.1 发现

如果需要,您还可以将端点添加到发现文档中,例如:

services.AddIdentityServer(options =>
{
    options.Discovery.CustomEntries.Add("custom_endpoint", "~/api/custom");
})

github地址

posted @ 2019-04-28 22:13  ThinkJay  阅读(365)  评论(0编辑  收藏  举报