Nerzal / gocloak

golang keycloak client
Apache License 2.0
1.01k stars 275 forks source link

Best practices for claim parse #481

Open alimoli opened 1 month ago

alimoli commented 1 month ago

Is your feature request related to a problem? Please describe. I am pretty new in Keycloak, so forgive me if my request is absurd. I have a realm where a user belongs to a group inheriting the role admin. Once the login is done, the access token coming from the IdP contains correctly the admin role.

[...]
realm_access": {
    "roles": [
      "offline_access",
      "admin",  <----- ✅ 
      "uma_authorization",
      "default-roles-xxx"
    ]
  },
  "resource_access": {
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },
  "scope": "email profile",
[...]

Everything is good, but now I would like to understand the best practice to extract the claims from this token structure. This is useful for the next step where I integrate the middleware based on the role.

Describe the solution you'd like Probably there is already a way implemented in this library to extract the claims into a structure, but I have not seen any standard way to do so in the issues/documentation/examples. I would expect a concrete structure that reflects the basic access token structure coming from KeyCloak. In the case of custom claims, then I imagine the best is to use the DecodeAccessTokenCustomClaims.

Describe alternatives you've considered The temporary solution I adopted is the following:

decodedAccessToken, claims, err := auth.keycloak.Gocloak.DecodeAccessToken(context.Background(), token, auth.keycloak.Realm, "")
if err != nil {
    c.JSON(http.StatusUnauthorized, gin.H{"error": fmt.Sprintf("Invalid or malformed token: %s", err.Error())})
    c.Abort()
    return
}

// Use mapstructure library to decode to a struct