添加id_token作为声明AspNetCore OpenIdConnect中间件

时间:2016-06-01 18:54:36

标签: claims-based-identity openid-connect identityserver3 .net-core-rc2

我在发送退出请求时尝试设置IdTokenHint。在之前的Microsoft.Owin.Security.OpenIdConnect中间件中,我可以使用id_token通知在SecurityTokenValidated方法中将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上。我错过了什么?

1 个答案:

答案 0 :(得分:0)

关于上面的代码,至少在ASP.NET Core 2.1版中,可以通过context.Properties.GetTokenValue(...)(而不是用户声明)来访问ID令牌。

但是,就像布罗克·艾伦(Brock Allen)在comment to your question中所说的那样,OpenIdConnectHandler将在登出时自动包含idTokenHint。但是,这使我今天感到困扰了几个小时,除非将OpenIdConnectOptions.SaveTokens设置为true,否则以后将无法保存令牌。默认值为false

因此,如果SaveTokenstrue,则处理程序将自动包含idTokenHint,并且您可以通过id token手动访问context.Properties.GetTokenValue(...)