How do I get the claims from an openid access token in asp.net core?

3.2k Views Asked by At

My application authenticates using OpenId like this:

services.AddAuthentication(o =>
{
    o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(o =>
{
    o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.Scope.Add("openid");
    o.Scope.Add("permissions");
    o.Authority = "https://localhost:44305";
    o.ClientId = "MyTestClient";
    o.ClientSecret = "MyTestClientSecret";
    o.ResponseType = OpenIdConnectResponseType.IdTokenToken;
});

When I check the User object after authenticating, it only has claims from the ID token, not the access token. How do I get the claims from the access token?

2

There are 2 best solutions below

1
On

You can use the OnTokenResponseReceived event from OpenIdConnectOptions.Events

services.AddAuthentication(o =>
{
    o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(o =>
{
    o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    o.Scope.Add("openid");
    o.Scope.Add("permissions");
    o.Authority = "https://localhost:44305";
    o.ClientId = "MyTestClient";
    o.ClientSecret = "MyTestClientSecret";
    o.ResponseType = OpenIdConnectResponseType.IdTokenToken;
    o.Events = new OpenIdConnectEvents
    {

        OnTokenResponseReceived = ctx =>
        {
            var handler = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadJwtToken(ctx.TokenEndpointResponse.AccessToken);

            //jsonToken.Claims <--here you go, update the ctx.Principal if necessary.


            return Task.CompletedTask;
        }
    };

});
0
On

I believe you need to intercept the OnAuthorizationCodeReceived event from AddOpenIdConnect(). From there you should have access to ctx.ProtocolMessage.Code which is the AuthorizationCode used with AcquireTokenByAuthorizationCodeAsync() to generate further tokens. You also need to set ResponseType to "code id_token" in order that a code is also generated for you. A good tutorial for this is https://joonasw.net/view/aspnet-core-2-azure-ad-authenticatio. Hope this helps