Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add custom claims from Keycloak user token #1917

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading