/* Copyright 2020-2023 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" "net/http" "github.com/gorilla/sessions" "github.com/lestrrat-go/jwx/jwk" log "github.com/sirupsen/logrus" "golang.org/x/oauth2" "code.cacert.org/cacert/oidc-demo-app/services" ) const ( sessionKeyAccessToken = iota sessionKeyRefreshToken sessionKeyIDToken sessionRedirectTarget ) type OidcCallbackHandler struct { keySet jwk.Set logger *log.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.WithError(err).Error("could not perform token exchange") http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } session, err := services.GetSessionStore().Get(r, "resource_session") if err != nil { c.logger.WithError(err).Error("could not get session store") http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } if err = c.storeTokens(session, tok); err != nil { c.logger.WithError(err).Error("could not store token in session") http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } if err = session.Save(r, w); err != nil { c.logger.WithError(err).Error("could not save session") http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } if redirectTarget, ok := session.Values[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[sessionKeyAccessToken] = tok.AccessToken session.Values[sessionKeyRefreshToken] = 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[sessionKeyIDToken] = idToken oidcToken, err := ParseIDToken(idToken, c.keySet) if err != nil { return fmt.Errorf("could not parse ID token: %w", err) } c.logger.WithFields(log.Fields{ "sub": oidcToken.Subject(), "aud": oidcToken.Audience(), "issued_at": oidcToken.IssuedAt(), "iss": oidcToken.Issuer(), "not_before": oidcToken.NotBefore(), "exp": oidcToken.Expiration(), }).Debug("receive OpenID Connect ID Token") return nil } func NewCallbackHandler(logger *log.Logger, keySet jwk.Set, oauth2Config *oauth2.Config) *OidcCallbackHandler { return &OidcCallbackHandler{ keySet: keySet, logger: logger, oauth2Config: oauth2Config, } }