Warm tip: This article is reproduced from stackoverflow.com, please click
keycloak

Keycloak: mapping username on subject claim

发布于 2020-03-31 23:00:59

I need to configure Keycloak so that it creates a JWT with claim "sub" populated with the username, instead of the default userId in sub.

It means that instead of this token:

{
    "jti": "b1384883-9b59-4788-b09f-98b40b7e3c3b",
   ...
    "sub": "fbdb4e4a-6e93-4b08-a1e7-0b7bd08520a6",
    "preferred_username": "m123456"
}

I need to receive:

 {
    "jti": "b1384883-9b59-4788-b09f-98b40b7e3c3b",
    ...
    "sub": "m123456",
    "preferred_username": "m123456"
 }

Could you please suggest how to do that?

I tried username mapper, but it adds a second "sub" claim and with the jwt is not valid.

Questioner
Nicola Ben
Viewed
112
Nicola Ben 2019-06-19 22:02

I solved in this way.

1) In "Clients" configure section choose your client

2) Go to "Mappers" tab and Create a new "Script Mapper"

3) An editable section called "Script" will open and inside it you can edit the following line: token.setSubject(user.getUsername());

4) Now my token contains "sub": "user123456"

5) Take a look to this image

enter image description here