【问题标题】:.NET IdentityServer4 OpenIdConnect with Discord.NET IdentityServer4 OpenIdConnect 与 Discord
【发布时间】:2022-10-27 16:29:18
【问题描述】:

我正在尝试使用 IdentityServer 并一直密切关注 readthedocs 上的指南。我正在添加外部身份提供者,并将我想要支持的所有身份提供者添加到 IdentityServer 项目中。

我特别想包含来自 Discord 的“公会”,然后根据用户在特定公会上的角色在我的网络应用程序中进行基于角色的授权。 Discord 列出了各种允许的范围:

所以我包含了 AspNet.Security.OAuth.Discord 包并为公会添加了一个 IdentityResource:

public static class AuthConfig
{
    public static IEnumerable<IdentityResource> IdentityResources =>
        new List<IdentityResource>
        { 
            new IdentityResources.OpenId(),
            new IdentityResources.Address(),
            new IdentityResources.Email(),
            new IdentityResources.Profile(),
            new  IdentityResource()
            {
                Name = "guilds",
                DisplayName = "Discord Guilds",
                Description = "All of the Discord Guilds the user belongs to",
                Required = true,
                Emphasize = true,
                UserClaims = new[] { "name" } // <<< Not sure how I find the claims on the discord api doco
            }
        };

    .
    .
    .
}

然后,这允许我在启动 IdentityServer 项目时将范围添加到我的 discord 选项:

public void ConfigureServices(IServiceCollection services)
{
    // uncomment, if you want to add an MVC-based UI
    services.AddControllersWithViews();

    services.AddAuthentication()
        .AddDiscord("Discord", options =>
        {
            options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
            options.ClientId = "<my client id>";
            options.ClientSecret = "<my client secret>";
            options.Scope.Add("guilds");
        })

当我登录时,uri 添加了公会范围,我在确认对话框中收到警告:

但是当我查看我的声明内容时,我什么也看不到。 如果我添加一个标准的 oidc 之一电子邮件虽然确实显示了。

如果我遵循 IdentityResources.Email 的定义,那么我会在 IdentityServer4.ConstantsScopeToClaimsMapping 属性上看到这些声明

但我不确定如何确定这些声明对于 Discord guilds scope 应该是什么......这甚至是问题所在。

谁能指出我正确的方向?

【问题讨论】:

    标签: oauth-2.0 discord identityserver4 openid-connect


    【解决方案1】:

    声明和范围是不同但相关的东西。

    范围是声明,它谈论您的访问范围。

    当您请求“公会”范围时,这意味着您的令牌将能够访问该范围内的信息。但这并不一定意味着信息将在令牌或 user_info 响应的声明中呈现。

    相反,要获取“行会”信息,您需要做的是使用令牌使用他们的 API。

    Discord Developer Portal - Guilds

    获取当前用户公会
    GET /用户/@我/行会

    返回当前用户所属的部分公会对象的列表。

    需要行会 OAuth2 范围.

    【讨论】:

    • 谢谢,我试过这样做但是当我通过 /users/@me/guilds 调用传递我的 access_token 时,我得到了未经授权的 401。这是 Discord 与 guilds 角色的令牌问题,所以我不确定是什么继续。
    • 您需要使用来自 discord 的 access_token,而不是您在身份服务器上创建的那个。