Search code examples
jwtkeycloakopenid-connectaccess-tokenpyjwt

How to modify existing claims in JWT from Keycloak for OIDC flow?


I'm generating JWTs for a service for authentication and we're using Keycloak as the OAuth server.

I've set up a realm R, a client C, and a user U. I setup a protocol mapper to include "C" in the "aud". I generated the JWTtoken for U and when I check the payload, I see "aud": ["C", "account"]. Which is great, I wanted C to be present. But I do not want "account" to be present in the "aud".

How do I configure this in keycloak? Similarly, the scope reads - "scope": "email profile test-client-rhs" and I wish to remove "email profile" from it. I've been googling around a lot and trying out different stuff in Keycloak but I can't get this to work somehow.


Solution

  • I generated the JWTtoken for U and when I check the payload, I see "aud": ["C", "account"]. Which is great, I wanted C to be present. But I do not want "account" to be present in the "aud".

    Instead of an audience Mapper you can use a Hardcoded claim Mapper with:

    • Token Claim Name set to aud
    • Claim value set to C
    • Add to access token set to ON

    this mapper will override the original claim "aud": "account" with "aud": "C"

    Like so:

    (Old Keycloak UI)

    enter image description here

    (For the NEW Keycloak UI)

    • Go to the tab Client Scopes
    • Click on the scope -dedicated (e.g., test-dedicated in my example)

    enter image description here

    • Click on Configure a new mapper

    enter image description here

    • Select Hardcoded claim, and then fill up
    • Click on Save.

    The client will be the client that you are using to authenticate against.

    How do I configure this in keycloak? Similarly, the scope reads - "scope": "email profile test-client-rhs" and I wish to remove "email profile" from it.

    For this you need to go to:

    • The realm where the client is
    • Go to clients and select the client
    • Click on the tab "Client Scopes"

    (For the Old Keycloak UI)

    • Remove the scopes email and profile from "Assigned Default Client Scopes"

    like so:

    enter image description here

    (For the NEW Keycloak UI)

    • change the scopes email and profile from Default to Optional, Like so:

    enter image description here