簡體   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