繁体   English   中英

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

[英]Identity Server 4 Adding claims after authentication from a UI

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

我想在此过程中添加一个步骤,在重定向回客户端之前,用户界面会显示 select 的选项列表,结果将其添加为声明,然后在客户端中可用。 我看到这一点的方式是推迟发生在 ExternalController 中的第 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 核心 2.0 开始,大多数声明类型都被自动剥离以节省膨胀。 您必须特别指定 map 是您在客户端的 OpenID Connect 设置中所追求的。 请参阅此主题: https://github.com/aspnet/Security/issues/1449

只需像您在此处那样操作当前用户:

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

不会影响登录用户或其令牌/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;
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM