Skip to content

Commit

Permalink
Merge pull request #81 from Dewberry/patch/auth-aud
Browse files Browse the repository at this point in the history
  • Loading branch information
ar-siddiqui authored Dec 15, 2023
2 parents 34da1f2 + 8d9b724 commit da09335
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
25 changes: 24 additions & 1 deletion api/auth/auth.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package auth

import (
"encoding/json"
"net/http"
"strings"

Expand All @@ -14,11 +15,33 @@ type AuthStrategy interface {
SetUserRolesHeader(c echo.Context, claims *Claims) error
}

type Audience []string

// aud in token can be []string or string, therefore we need a custom unmarshaler.
// jwt package uses the json package for unmarshalling JSON into Go structs.
func (a *Audience) UnmarshalJSON(data []byte) error {
// Try to unmarshal data into a slice of strings
var audienceSlice []string
if err := json.Unmarshal(data, &audienceSlice); err == nil {
*a = audienceSlice
return nil
}

// If the above fails, try to unmarshal as a single string
var singleAud string
if err := json.Unmarshal(data, &singleAud); err != nil {
return err
}

*a = []string{singleAud}
return nil
}

type Claims struct {
UserName string `json:"preferred_username"`
Email string `json:"email"`
RealmAccess map[string][]string `json:"realm_access"`
Audience []string `json:"aud,omitempty"`
Audience Audience `json:"aud,omitempty"`
jwt.StandardClaims
}

Expand Down
10 changes: 3 additions & 7 deletions api/auth/keycloak.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ func (kas *KeycloakAuthStrategy) getPublicKeyStr(kid string) string {
}

func (kas *KeycloakAuthStrategy) ValidateToken(tokenString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
var claims Claims
token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
Expand All @@ -128,12 +129,7 @@ func (kas *KeycloakAuthStrategy) ValidateToken(tokenString string) (*Claims, err
return nil, fmt.Errorf("invalid JWT")
}

claims, ok := token.Claims.(*Claims)
if !ok {
return nil, fmt.Errorf("invalid JWT claims")
}

return claims, nil
return &claims, nil
}

// Validate X-ProcessAPI-User-Email header against user from claims
Expand Down

0 comments on commit da09335

Please sign in to comment.