github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/plugin/oauth2/middleware_secret.go (about) 1 package oauth2 2 3 import ( 4 "encoding/base64" 5 "fmt" 6 "net/http" 7 8 log "github.com/sirupsen/logrus" 9 ) 10 11 // SecretMiddleware is used as a helper for client applications that don't want to send the client secret 12 // on the request. The applications should only send the `client_id` and this middleware will try to find 13 // the secret on it's configuration. 14 // If the secret is found then the middleware will build a valid `Authorization` header to be sent to the 15 // authentication provider. 16 // If the secret is not found then and error is returned to the client application. 17 type SecretMiddleware struct { 18 oauth *Spec 19 } 20 21 // NewSecretMiddleware creates an instance of SecretMiddleware 22 func NewSecretMiddleware(oauth *Spec) *SecretMiddleware { 23 return &SecretMiddleware{oauth} 24 } 25 26 // Handler is the middleware method. 27 func (m *SecretMiddleware) Handler(handler http.Handler) http.Handler { 28 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 29 log.Debug("Starting Oauth2Secret middleware") 30 31 if "" != r.Header.Get("Authorization") { 32 log.Debug("Authorization is set, proxying") 33 handler.ServeHTTP(w, r) 34 return 35 } 36 37 clientID := r.URL.Query().Get("client_id") 38 if "" == clientID { 39 log.Debug("ClientID not set, proxying") 40 handler.ServeHTTP(w, r) 41 return 42 } 43 44 clientSecret, exists := m.oauth.Secrets[clientID] 45 if false == exists { 46 panic(ErrClientIDNotFound) 47 } 48 49 m.changeRequest(r, clientID, clientSecret) 50 handler.ServeHTTP(w, r) 51 }) 52 } 53 54 // changeRequest modifies the request to add the Authorization headers. 55 func (m *SecretMiddleware) changeRequest(req *http.Request, clientID, clientSecret string) { 56 log.Debug("Modifying request") 57 authString := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", clientID, clientSecret))) 58 req.Header.Set("Authorization", fmt.Sprintf("Basic %s", authString)) 59 }