在IdentityServer4中保护客户端

时间:2018-06-07 19:44:59

标签: .net oauth-2.0 identityserver4 openid-connect

我有以下情况:

enter image description here

我对如何在IdentityServer4中设置 API 2 感到困惑,因为它让我觉得它们都是Client(因为它消耗了它) API 1 )和ApiResource提供的资源(因为我想要保护它,以便只有登录的用户才能访问它)。

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

处理此方案的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

基本上,您需要使用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应该是不同的。然后,您的javascript客户端在Identity Server端构建时,应该被允许访问这两个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"
        }
    }

此代码来自official documentation

然后在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();
}

这应该适合你。