Skip to content

Commit

Permalink
feat: Add custom claims from Keycloak user token
Browse files Browse the repository at this point in the history
  • Loading branch information
wdoppenberg committed Jan 17, 2025
1 parent a4c692f commit 79d1160
Showing 1 changed file with 40 additions and 4 deletions.
44 changes: 40 additions & 4 deletions internal/api/provider/keycloak.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package provider

import (
"context"
"encoding/json"
"errors"
"strings"

Expand All @@ -16,10 +17,33 @@ type keycloakProvider struct {
}

type keycloakUser struct {
Name string `json:"name"`
Sub string `json:"sub"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
Sub string `json:"sub"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
RawClaims map[string]interface{} `json:"-"`
}

func (u *keycloakUser) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &u.RawClaims); err != nil {
return err
}

// Extract known fields
if v, ok := u.RawClaims["name"].(string); ok {
u.Name = v
}
if v, ok := u.RawClaims["sub"].(string); ok {
u.Sub = v
}
if v, ok := u.RawClaims["email"].(string); ok {
u.Email = v
}
if v, ok := u.RawClaims["email_verified"].(bool); ok {
u.EmailVerified = v
}

return nil
}

// NewKeycloakProvider creates a Keycloak account provider.
Expand Down Expand Up @@ -72,6 +96,17 @@ func (g keycloakProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*
return nil, err
}

customClaims := make(map[string]interface{})
standardClaims := map[string]bool{
"name": true, "sub": true, "email": true, "email_verified": true,
}

for k, v := range u.RawClaims {
if !standardClaims[k] {
customClaims[k] = v
}
}

data := &UserProvidedData{}
if u.Email != "" {
data.Emails = []Email{{
Expand All @@ -87,6 +122,7 @@ func (g keycloakProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*
Name: u.Name,
Email: u.Email,
EmailVerified: u.EmailVerified,
CustomClaims: customClaims,

// To be deprecated
FullName: u.Name,
Expand Down

0 comments on commit 79d1160

Please sign in to comment.