首页 > 解决方案 > 在 IdentityServer4 中保护客户端

问题描述

我有以下情况:

在此处输入图像描述

我对如何在 IdentityServer4 中设置API 2感到困惑,因为在我看来它既是一个Client(因为它正在消耗API 1提供的资源)又是一个ApiResource(因为我想保护它以便只记录-在用户可以访问它)。

我考虑过将API 2设置为 aClient并使用 cookie 身份验证对其进行保护。我认为这与他们在示例中的 MvcClient 中所做的类似。但是,我不喜欢它,因为有关用户的所有信息都存储在服务器端,所以我的 JavaScript 应用程序无法知道用户的姓名、电子邮件等。

处理这种情况的最佳方法是什么?

标签: .netoauth-2.0identityserver4openid-connect

解决方案


基本上,您需要使用 Identity Server 保护您的两个 API。就像是:

API 1 Startup.cs

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) 
.AddIdentityServerAuthentication(options => 
{ 
    options.Authority = "https://localhost:5000"; 
    options.SupportedTokens = SupportedTokens.Both; 
    options.RequireHttpsMetadata = false; 
    options.ApiName = "api1"; 
});

API 2 相同,但options.ApiName应该不同。然后,当在 Identity Server 端构建时,您的 javascript 客户端应该被允许访问这 2 个 api(允许的范围):

new Client
    {
        ClientId = "your.js.client.id",

        AllowedGrantTypes = GrantTypes.Implicit,
        AllowAccessTokensViaBrowser = true,

        RedirectUris =           { "http://localhost:5003/callback.html" },
        PostLogoutRedirectUris = { "http://localhost:5003/index.html" },
        AllowedCorsOrigins =     { "http://localhost:5003" },

        AllowedScopes =
        {
            "api2",
            "api1"
        }
    }

此代码来自官方文档

然后在 API 2 中,当你想调用 API 1 的控制器时,你需要类似:

var client = new HttpClient();
client.SetBearerToken(accessToken);
client.GetStringAsync("https://localhost/api1/test");

你在哪里得到access_token

[Authorize]
public async Task<IActionResult> ControllerMethodInApi2()
{
    var accessToken = await context.HttpContext.GetTokenAsync("access_token"); 

    return View();
}

这应该适合你。


推荐阅读