Merge pull request #473 from enj/enj/r/oidc_discovery_json

oidc discovery: encode metadata once and reuse
This commit is contained in:
Mo Khan 2021-03-03 14:12:33 -05:00 committed by GitHub
commit 4f700d4811
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

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
}
})
}