github.com/louisevanderlith/droxolite@v1.20.2/open/jwks.go (about) 1 package open 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "github.com/dgrijalva/jwt-go" 8 "net/http" 9 ) 10 11 type Jwks struct { 12 Keys []JSONWebKeys `json:"keys"` 13 } 14 15 type JSONWebKeys struct { 16 Kty string `json:"kty"` 17 Kid string `json:"kid"` 18 Use string `json:"use"` 19 N string `json:"n"` 20 E string `json:"e"` 21 X5c []string `json:"x5c"` 22 } 23 24 func getPemCert(issUrl string, token *jwt.Token) (string, error) { 25 cert := "" 26 certUrl := fmt.Sprintf("%s/protocol/openid-connect/certs", issUrl) 27 resp, err := http.Get(certUrl) 28 29 if err != nil { 30 return cert, err 31 } 32 defer resp.Body.Close() 33 34 var jwks = Jwks{} 35 err = json.NewDecoder(resp.Body).Decode(&jwks) 36 37 if err != nil { 38 return cert, err 39 } 40 41 for k, _ := range jwks.Keys { 42 if token.Header["kid"] == jwks.Keys[k].Kid { 43 cert = "-----BEGIN CERTIFICATE-----\n" + jwks.Keys[k].X5c[0] + "\n-----END CERTIFICATE-----" 44 } 45 } 46 47 if cert == "" { 48 err := errors.New("unable to find appropriate key") 49 return cert, err 50 } 51 52 return cert, nil 53 }