Skip to content

Instantly share code, notes, and snippets.

@strikeout
Forked from webdeb/Hasura Keycloak.md
Created June 20, 2020 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save strikeout/0c6bf4f57437bf8b2f7cbb97875fd451 to your computer and use it in GitHub Desktop.
Save strikeout/0c6bf4f57437bf8b2f7cbb97875fd451 to your computer and use it in GitHub Desktop.
Basic Keycloak Script Mapper to provide Hasura claims

Steps to provide Hasura Claims in Keycloak generated JWT

  1. Create your realm / client
  2. Inside client configuration go to "Mappers"
  3. Click on "Create"
  4. Name it "hasura"
  5. Choose Mapper Type "Script Mapper"
  6. Add following script to demonstrate how it works
/**
 * Available variables: 
 * user - the current user (UserModel)
 * realm - the current realm (RealmModel)
 * token - the current token (TokenModel)
 * userSession - the current userSession (UserSessionModel)
 * keycloakSession - the current keycloakSession (KeycloakSessionModel)
 */


//insert your code here...
var roles = [];
for each (var role in user.getRoleMappings()) roles.push(role.getName());
token.setOtherClaims("https://hasura.io/jwt/claims", {
    "x-hasura-user-id": user.getId(),
    "x-hasura-allowed-roles": Java.to(roles, "java.lang.String[]"),
    "x-hasura-default-role": "user",
});

Thats it, the next step is just to verify your settings

  1. Go to clients -> your-client -> Scopes -> Evaluate
  2. Select an user, and see the generated JWT payload in "Generated Access Token" Tab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment