c# - Identity Server 4 从 UI 进行身份验证后添加声明

标签 c# asp.net-core azure-active-directory identityserver4 openid-connect

我正在 MVC Core 应用程序中实现 Identity Server 4。我将 Azure Active Directory 作为外部提供商,到目前为止,所有这些都运行良好。我还实现了 QuickStart UI(按照 https://github.com/IdentityServer/IdentityServer4.Quickstart.UI#quickstart-ui-for-identityserver4 )

我想在重定向回客户端之前在此过程中添加一个步骤,其中用户界面会显示可供选择的选项列表,结果会添加为随后在客户端中可用的声明。我的看法是推迟外部 Controller 中第 143 行发生的重定向 ( https://github.com/IdentityServer/IdentityServer4.Quickstart.UI/blob/main/Quickstart/Account/ExternalController.cs )

我尝试重定向到自定义操作并获取用户输入,如下所示:

[HttpGet]
public async Task<IActionResult> MakeAChoice(string returnUrl)
{
     //simple view model to maintain the returnUrl
     var vm = BuildMakeAChoiceViewModel(returnUrl);
     return View(vm);
}

[HttpPost]
public async Task<IActionResult> MakeAChoice(MakeAChoiceViewModel model, string choice)
{
     //method one:
     HttpContext.User.Claims.Append(new Claim("chosen_value", choice));

     //method two:
     HttpContext.User.Identities.FirstOrDefault().AddClaim(new Claim("chosen_value", choice));
     return Redirect(model.ReturnUrl);
}

重定向工作得很好,所以我能够中断整个过程,但仍然完成链并返回到客户端应用程序,没有问题。不幸的是,这个声明并没有返回给客户。

想要此 UI 驱动步骤的原因是,实现了 Identity Server 的应用程序包含其自己的数据库以及应用程序所需的详细信息,但只有那些首先可以通过 Azure 进行身份验证的人才能访问。此附加声明的数据也可能会发生很大的变化,这就是为什么用户在这里的选择很重要。

编辑:提供的答案让我克服了这一障碍,不幸的是我仍然无法在客户端中检索自定义声明。事实证明,从 .net core 2.0 开始,大多数声明类型都会自动删除以节省膨胀。您必须在客户端的 OpenID Connect 设置中专门映射您想要的内容。请参阅此主题:https://github.com/aspnet/Security/issues/1449

最佳答案

就像在这里操作一样操作当前用户:

HttpContext.User.Identities.FirstOrDefault().AddClaim(new Claim("chosen_value", choice));

不会影响登录用户或其 token /cookie。您需要在调用之前添加自己的声明:

await HttpContext.SignInAsync(isuser, props);

作为替代方案,如果您要添加的声明特定于一个或几个客户端,您可以通过添加自己的 OnTicketReceived 事件处理程序来在客户端执行此操作,例如:

options.Events = new OpenIdConnectEvents
{
    OnTicketReceived = e =>
    {
        if (!e.Principal.HasClaim(c => c.Type == "bonuslevel"))
        {
            //Lookup bonus level.....
            e.Principal.Identities.First().AddClaim(new Claim("bonuslevel", "12345"));
        }
        return Task.CompletedTask;
    }
};

关于c# - Identity Server 4 从 UI 进行身份验证后添加声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62997101/

相关文章:

Azure ServiceBus 单元测试

asp.net-core - 无法运行 dnx 控制台应用程序

Azure AD 服务器身份验证,无权限查看目录

c# - 如何将 ClosedXML 中的货币格式化为数字

c# - Visual Studio 2013 编译器警告未显示

C# 是否有异常概述?

angular - 无法识别的配置部分 system.webServer。 (对于 Angular 核心 - Angular)

asp.net-core - Blazor 独立 WebAssembly 代表登录用户调用安全核心 API

azure - 在 JWT token 中包含 AAD 组名称

c# - 在 OnlineIdConnectedStateChange 触发后检查用户是否登录