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
1 changed files with 25 additions and 14 deletions

View File

@ -5,6 +5,7 @@
package discovery
import (
"bytes"
"encoding/json"
"net/http"
@ -40,14 +41,6 @@ type Metadata struct {
// NewHandler returns an http.Handler that serves an OIDC discovery endpoint.
func NewHandler(issuerURL string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodGet {
http.Error(w, `Method not allowed (try GET)`, http.StatusMethodNotAllowed)
return
}
oidcConfig := Metadata{
Issuer: issuerURL,
AuthorizationEndpoint: issuerURL + oidc.AuthorizationEndpointPath,
@ -60,8 +53,26 @@ func NewHandler(issuerURL string) http.Handler {
ScopesSupported: []string{"openid", "offline"},
ClaimsSupported: []string{"groups"},
}
if err := json.NewEncoder(w).Encode(&oidcConfig); err != nil {
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 {
http.Error(w, `Method not allowed (try GET)`, http.StatusMethodNotAllowed)
return
}
if encodeErr != nil {
http.Error(w, encodeErr.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err := w.Write(encodedMetadata); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
}