oidc-demo-app/internal/handlers/oidc_callback.go
Jan Dittberner c4724723b6 Switch from logrus to log/slog
Use log/slog from the Go standard library to reduce dependencies.
2024-05-12 12:02:27 +02:00

165 lines
4 KiB
Go

/*
Copyright CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package handlers
import (
"fmt"
"log/slog"
"net/http"
"time"
"github.com/gorilla/sessions"
"github.com/lestrrat-go/jwx/jwk"
"golang.org/x/oauth2"
"code.cacert.org/cacert/oidc-demo-app/internal/services"
)
type OidcCallbackHandler struct {
keySet jwk.Set
logger *slog.Logger
oauth2Config *oauth2.Config
}
func (c *OidcCallbackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if r.URL.Path != "/callback" {
http.NotFound(w, r)
return
}
errorText := r.URL.Query().Get("error")
errorDescription := r.URL.Query().Get("error_description")
code := r.URL.Query().Get("code")
if c.handleCallbackError(errorText, errorDescription, r) {
return
}
tok, err := c.oauth2Config.Exchange(r.Context(), code)
if err != nil {
c.logger.Error("could not perform token exchange", "error", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
session, err := GetSession(r)
if err != nil {
c.logger.Error("could not get session", "error", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if err = c.storeTokens(session, tok); err != nil {
c.logger.Error("could not store token in session", "error", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if err = session.Save(r, w); err != nil {
c.logger.Error("could not save session", "error", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if redirectTarget, ok := session.Values[services.SessionRedirectTarget]; ok {
if v, ok := redirectTarget.(string); ok {
w.Header().Set("Location", v)
w.WriteHeader(http.StatusFound)
return
}
}
w.Header().Set("Location", "/")
w.WriteHeader(http.StatusFound)
}
func (c *OidcCallbackHandler) handleCallbackError(errorText string, errorDescription string, r *http.Request) bool {
if errorText != "" {
errorDetails := &ErrorDetails{
ErrorMessage: errorText,
}
if errorDescription != "" {
errorDetails.ErrorDetails = []string{errorDescription}
}
GetErrorBucket(r).AddError(errorDetails)
return true
}
return false
}
func (c *OidcCallbackHandler) storeTokens(
session *sessions.Session,
tok *oauth2.Token,
) error {
session.Values[services.SessionAccessToken] = tok.AccessToken
session.Values[services.SessionRefreshToken] = tok.RefreshToken
idTokenValue := tok.Extra("id_token")
idToken, ok := idTokenValue.(string)
if !ok {
return fmt.Errorf("ID token value %v is not a string", idTokenValue)
}
session.Values[services.SessionIDToken] = idToken
session.Options.MaxAge = int(time.Until(tok.Expiry).Seconds())
oidcToken, err := services.ParseIDToken(idToken, c.keySet)
if err != nil {
return fmt.Errorf("could not parse ID token: %w", err)
}
c.logger.Debug(
"receive OpenID Connect ID Token",
"sub", oidcToken.Subject(),
"aud", oidcToken.Audience(),
"issued_at", oidcToken.IssuedAt(),
"iss", oidcToken.Issuer(),
"not_before", oidcToken.NotBefore(),
"exp", oidcToken.Expiration(),
)
return nil
}
func NewCallbackHandler(logger *slog.Logger, keySet jwk.Set, oauth2Config *oauth2.Config) *OidcCallbackHandler {
return &OidcCallbackHandler{
keySet: keySet,
logger: logger,
oauth2Config: oauth2Config,
}
}