Add support for array of audiences

See https://github.com/dgrijalva/jwt-go/pull/308
This commit is contained in:
wpetit 2020-06-21 14:01:47 +02:00
parent 7557a4c29c
commit b37171c19f

View File

@ -3,6 +3,8 @@ package auth
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strconv" "strconv"
@ -28,6 +30,30 @@ type firebasePKCache struct {
var firebasePublicKeys firebasePKCache var firebasePublicKeys firebasePKCache
type standardClaims struct {
jwt.StandardClaims
Audience []string `json:"aud,omitempty"`
}
func (c *standardClaims) MatchAudience(audience string) bool {
matchLegacy := c.StandardClaims.Audience == audience
if matchLegacy {
return true
}
if c.Audience == nil {
return false
}
for _, tokenAudience := range c.Audience {
if audience == tokenAudience {
return true
}
}
return false
}
func JwtHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) { func JwtHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
var key interface{} var key interface{}
var jwtProvider int var jwtProvider int
@ -99,17 +125,16 @@ func JwtHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
} }
} }
token, err := jwt.ParseWithClaims(tok, &jwt.StandardClaims{}, keyFunc) token, err := jwt.ParseWithClaims(tok, &standardClaims{}, keyFunc)
if err != nil { if err != nil {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
return return
} }
if claims, ok := token.Claims.(*jwt.StandardClaims); ok { if claims, ok := token.Claims.(*standardClaims); ok {
ctx := r.Context() ctx := r.Context()
if ac.JWT.Audience != "" && claims.Audience != ac.JWT.Audience { if ac.JWT.Audience != "" && !claims.MatchAudience(ac.JWT.Audience) {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
return return
} }