簡體   English   中英

添加 id_token 作為聲明 AspNetCore OpenIdConnect 中間件

[英]Add id_token as claim AspNetCore OpenIdConnect middleware

我正在嘗試在發送注銷請求時設置IdTokenHint 在之前的Microsoft.Owin.Security.OpenIdConnect中間件中,我可以使用SecurityTokenValidated通知將id_token設置為SecurityTokenValidated方法中的聲明,方法如下:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    ...
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        //Perform claims transformation
        SecurityTokenValidated = async notification =>
        {
            ...
            notification.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));
        },
        RedirectToIdentityProvider = async n =>
        {
            if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
            {
                var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
                n.ProtocolMessage.IdTokenHint = idTokenHint;
             }
         }
    }
}

使用新的中間件Microsoft.AspNetCore.Authentication.OpenIdConnect (在 ASP.NET Core RC2 中)我在嘗試完成同樣的事情時遇到了麻煩。 我假設我應該像這樣利用Events

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ...
    Events = new OpenIdConnectEvents()
    {
         OnTokenValidated = context =>
         {
             ...
             context.SecurityToken.Payload.AddClaim(new Claim("id_token", context.ProtocolMessage.IdToken));
          },
          OnRedirectToIdentityProviderForSignOut = context =>
          {
                var idTokenHint = context.HttpContext.User.FindFirst("id_token").Value;
                context.ProtocolMessage.IdTokenHint = idTokenHint;
        }
     }
 }

我看到的問題是聲明不會保留在SecurityToken ,也不會在HttpContext.User上設置。 我錯過了什么?

關於上面的代碼,至少在 ASP.NET Core 2.1 版中,可以通過context.Properties.GetTokenValue(...) (而不是作為用戶聲明)訪問 ID 令牌。

但是,正如 Brock Allen 在對您的問題評論中所說, OpenIdConnectHandler將在OpenIdConnectHandler時自動包含idTokenHint 但是,今天這讓我咬了幾個小時,除非OpenIdConnectOptions.SaveTokens設置為true否則它不會保存令牌以備后用。 默認值為false

因此,如果SaveTokenstrue ,處理程序將自動包含idTokenHint ,您可以通過context.Properties.GetTokenValue(...)手動訪問id token

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM