Add registration handler and update routing for OIDC integration

This commit is contained in:
2025-02-25 19:02:27 -06:00
parent 0ba5eee981
commit 2d724763e1
2 changed files with 79 additions and 1 deletions

View File

@ -72,6 +72,7 @@ func (c *Config) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("/callback", c.CallbackHandler)
mux.HandleFunc("/logout", c.LogoutHandler)
mux.HandleFunc("/logout-callback", c.LogoutCallbackHandler)
mux.HandleFunc("/register", c.RegistrationHandler)
}
// Middleware returns an auth middleware function
@ -80,7 +81,8 @@ func (c *Config) Middleware() func(http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip authentication for public routes
if r.URL.Path == "/login" || r.URL.Path == "/callback" ||
r.URL.Path == "/logout" || r.URL.Path == "/logout-callback" {
r.URL.Path == "/logout" || r.URL.Path == "/logout-callback" ||
r.URL.Path == "/register" {
next.ServeHTTP(w, r)
return
}
@ -306,6 +308,55 @@ func (c *Config) LogoutCallbackHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/login", http.StatusFound)
}
// RegistrationHandler redirects to the OIDC registration page
func (c *Config) RegistrationHandler(w http.ResponseWriter, r *http.Request) {
// Generate random state, nonce, and code verifier for security
state := generateRandomString(32)
nonce := generateRandomString(32)
codeVerifier := generateRandomString(32)
hash := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.RawURLEncoding.EncodeToString(hash[:])
// Store state, nonce, and code verifier in session for verification
session, _ := c.Store.Get(r, c.SessionName)
session.Values["state"] = state
session.Values["nonce"] = nonce
session.Values["code_verifier"] = codeVerifier
if err := session.Save(r, w); err != nil {
log.Printf("Error saving session: %v", err)
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
// Build the registration URL using the specified registrations endpoint
baseURL := viper.GetString("issuer-url")
registrationURL, err := url.Parse(baseURL + "/protocol/openid-connect/registrations")
if err != nil {
log.Printf("Error parsing registration URL: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Add query parameters
q := registrationURL.Query()
q.Set("client_id", viper.GetString("client-id"))
q.Set("response_type", "code")
q.Set("scope", "openid email profile")
q.Set("redirect_uri", viper.GetString("hostname")+"/callback")
q.Set("state", state)
q.Set("nonce", nonce)
q.Set("code_challenge", codeChallenge)
q.Set("code_challenge_method", "S256")
registrationURL.RawQuery = q.Encode()
// Log for debugging
log.Printf("Redirecting to registration URL: %s", registrationURL.String())
// Redirect to registration page
http.Redirect(w, r, registrationURL.String(), http.StatusFound)
}
// Helper function to generate random strings
func generateRandomString(n int) string {
b := make([]byte, n)