How to add value to the JWT token's scope attribute?

i want to store some values (dynamically based on some user attributes value) in the JWT’s scope attribute

e.g.
{“jti”:“62c1bcfb-8916-423f-814d-e9db06e6ce03”,
“exp”:1579068936,“nbf”:0,“iat”:1579068636,
“iss”:“https://xxxx:8443/auth/realms/test-realm1”,
“scope”:“profile dynamic-spaced-separated-values-here
“aud”:“test-client-1”,“typ”:“Bearer”}

anybody know how can i achieve that? I have checked the script based OIDC mapper,
there is an IDToken object but i don’t know how to access the ‘scope’ attribute.

Can you please help? Thanks

for guys interested - found a possible solution for that changing the scope JWT attribute via script mapper, code as below…

var perms = user.getAttribute('PERMISSIONS');
if(token instanceof Java.type("org.keycloak.representations.AccessToken")){
  if (perms !== null && perms.size() > 0){
   //jdk.nashorn tread list as array via Java8 String API
   token.setScope(token.getScope() + " " + Java.type("java.lang.String").join(" ", perms));
  }    
}
else if(token instanceof Java.type("org.keycloak.representations.IDToken")){
   
    //for case of IDToken which do not have a getScope() method
    var scopes = token.getOtherClaims().get('scope');
    
    scopes = (scopes) ? scopes + " " + Java.type("java.lang.String").join(" ", perms) : Java.type("java.lang.String").join(" ", perms);
    
    token.setOtherClaims('scope', scopes);    
}

token.getIssuer();

Actually, i need to revise the usage of scope vs claims for fine-grained authorization control (which can’t model by the keycloak authorization mechanism).

2 Likes

@ping i am also looking forward for same want auth scopes in JWT token. thanks for sharing the code.

i have added your script into mapper of client inside toekn it’s adding

“claims”: “https://keycloak.mockharsh.tk/auth/realms/CAMPAIGN_REALM”, but i want auth scopes into token if you can please suggest.

@harshmanvar
sorry that i am not very understand your requirement…can further elaborate?

i am looking forward to add the auth scopes to the JWT token.

is it possible ?

i want to store auth scopes into the JWT’s scope attribute.

e.g.
{“jti”:“62c1bcfb-8916-423f-814d-e9db06e6ce03”,
“exp”:1579068936,“nbf”:0,“iat”:1579068636,
“iss”:“https://xxxx:8443/auth/realms/test-realm1”,
“scope”:“profile auth-scope-like(view or create)
“aud”:“test-client-1”,“typ”:“Bearer”}

You just need to:

  1. Define the scope (say scopeA) in the realm level “client scopes”
  2. In the client app setting page, add the newly created scopeA to the client app’s optional scope…

When you request for the token, supply the ‘scope=scopeA’ form post parameter…

Another approach, which bypass also such setting and blindly add the scope to the tokens is to get the request parameter from the underlying httpservletrequest object (via the keycloakSession javascript variable…need to test)

1 Like