oidc discovery: encode metadata once and reuse

Signed-off-by: Monis Khan <mok@vmware.com>
This commit is contained in:
Monis Khan 2021-03-03 13:37:43 -05:00
parent aa826a1579
commit d7edc41c24
No known key found for this signature in database
GPG Key ID: 52C90ADA01B269B8

View File

@ -5,6 +5,7 @@
package discovery package discovery
import ( import (
"bytes"
"encoding/json" "encoding/json"
"net/http" "net/http"
@ -40,28 +41,38 @@ type Metadata struct {
// NewHandler returns an http.Handler that serves an OIDC discovery endpoint. // NewHandler returns an http.Handler that serves an OIDC discovery endpoint.
func NewHandler(issuerURL string) http.Handler { func NewHandler(issuerURL string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { oidcConfig := Metadata{
w.Header().Set("Content-Type", "application/json") Issuer: issuerURL,
AuthorizationEndpoint: issuerURL + oidc.AuthorizationEndpointPath,
TokenEndpoint: issuerURL + oidc.TokenEndpointPath,
JWKSURI: issuerURL + oidc.JWKSEndpointPath,
ResponseTypesSupported: []string{"code"},
SubjectTypesSupported: []string{"public"},
IDTokenSigningAlgValuesSupported: []string{"ES256"},
TokenEndpointAuthMethodsSupported: []string{"client_secret_basic"},
ScopesSupported: []string{"openid", "offline"},
ClaimsSupported: []string{"groups"},
}
var b bytes.Buffer
encodeErr := json.NewEncoder(&b).Encode(&oidcConfig)
encodedMetadata := b.Bytes()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet { if r.Method != http.MethodGet {
http.Error(w, `Method not allowed (try GET)`, http.StatusMethodNotAllowed) http.Error(w, `Method not allowed (try GET)`, http.StatusMethodNotAllowed)
return return
} }
oidcConfig := Metadata{ if encodeErr != nil {
Issuer: issuerURL, http.Error(w, encodeErr.Error(), http.StatusInternalServerError)
AuthorizationEndpoint: issuerURL + oidc.AuthorizationEndpointPath, return
TokenEndpoint: issuerURL + oidc.TokenEndpointPath,
JWKSURI: issuerURL + oidc.JWKSEndpointPath,
ResponseTypesSupported: []string{"code"},
SubjectTypesSupported: []string{"public"},
IDTokenSigningAlgValuesSupported: []string{"ES256"},
TokenEndpointAuthMethodsSupported: []string{"client_secret_basic"},
ScopesSupported: []string{"openid", "offline"},
ClaimsSupported: []string{"groups"},
} }
if err := json.NewEncoder(w).Encode(&oidcConfig); err != nil {
w.Header().Set("Content-Type", "application/json")
if _, err := w.Write(encodedMetadata); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return
} }
}) })
} }