oidc-demo-app/internal/handlers/oidc_callback.go
Jan Dittberner 7ec9e393e0 Add separate protected resource page
This commit adds a separate protected resource page to demonstrate how
to selectively require logins.

Add code to improve client performance by providing modification timestamps
and Cache-Control headers for embedded static files.
2023-08-03 16:46:28 +02:00

164 lines
4.1 KiB
Go

/*
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"
"time"
"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/internal/services"
)
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 := GetSession(r)
if err != nil {
c.logger.WithError(err).Error("could not get session")
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[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.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,
}
}