Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add id_token as claim AspNetCore OpenIdConnect middleware

I am trying to set IdTokenHint when sending the sign out request. In the previous Microsoft.Owin.Security.OpenIdConnect middleware I would be able to set the id_token as a claim in the SecurityTokenValidated method using the SecurityTokenValidated notification by doing something like this:

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;
             }
         }
    }
}

With the new middleware Microsoft.AspNetCore.Authentication.OpenIdConnect (in ASP.NET Core RC2) I am having trouble trying to accomplish the same thing. I am assuming I should tap into the Events like so.

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;
        }
     }
 }

The problem I'm seeing is that the claims do not remain on the SecurityToken and don't get set on the HttpContext.User. What am I missing?

like image 788
LukeP Avatar asked Nov 20 '22 04:11

LukeP


1 Answers

Regarding your code above, at least in version 2.1 of ASP.NET Core, the ID token can be accessed via context.Properties.GetTokenValue(...) (rather than as a user claim).

And, as Brock Allen said in a comment to your question, the OpenIdConnectHandler will automatically include the idTokenHint on sign out. However, and this bit me for a few hours today, when the handler processes the sign-in callback, it will only save the tokens for later if OpenIdConnectOptions.SaveTokens is set to true. The default is false, i.e., the tokens are no longer available when you do the sign-out.

So, if SaveTokens is true, the handler will automatically include the idTokenHint on logout, and you can also manually access the id token via context.Properties.GetTokenValue(...).

like image 159
Fabian Schmied Avatar answered Dec 25 '22 23:12

Fabian Schmied