alexqq
alexqq

Reputation: 129

How to change token reponse in asp.net core 1?

I'm using JWT tokens and OpenIdConnectServer. All works very well, but i can't add custom properties in token response... Here are the result:

 resource": "resource_server_1",
   "token_type": "bearer",
  "access_token": "eyJhb....LSk5PQldEVVFaTllNU",
  "expires_in": "3600"

I want to add some properties like username or role... I'm trying to add through AuthenticationProperties, but it is doesn't work. Here my code:

 public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context)
        {
            ClaimsIdentity identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);
            identity.AddClaim(ClaimTypes.Name, "test", "token id_token");
            identity.AddClaim(ClaimTypes.Role, "test", "token id_token");


            var ticket = new AuthenticationTicket(
                new ClaimsPrincipal(identity),
                new AuthenticationProperties(new Dictionary<string, string>
                {
                    {"username", "test" }
                }),
                context.Options.AuthenticationScheme);

            ticket.SetResources(new[] { "resource_server_1" });


            context.Validated(ticket);

            return Task.FromResult<object>(null);

        }

Upvotes: 3

Views: 833

Answers (1)

K&#233;vin Chalet
K&#233;vin Chalet

Reputation: 42100

To add custom properties to token responses, you can take a look at this other SO question: Overriding TokenEndPoint in AspNet.Security.OpenIdConnect.Server

That said, this is not the approach I'd recommend. Instead, you should use the new id_token concept offered by OpenID Connect, which is also supported for the password flow in ASOS and that allows sharing user details between the authorization server and the client apps.

For that, add scope=openid to your token request and the OIDC server middleware will start returning a JSON Web Token you'll be able to read to extract user details like a username. Note that only claims specifying the id_token destination will be included in the identity token. Read this SO post for more info: https://stackoverflow.com/a/35041102/542757

(on a related note, you're not adding a ClaimTypes.NameIdentifier claim to your authentication ticket: this is not a legal operation as the OIDC server middleware needs a unique id to identify the user)

Upvotes: 3

Related Questions