Eric B
Eric B

Reputation: 4437

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

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?

Upvotes: 6

Views: 3756

Answers (2)

Steven.Xi
Steven.Xi

Reputation: 1830

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

});

Upvotes: 7

Matthew Christianson
Matthew Christianson

Reputation: 286

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

Upvotes: -1

Related Questions