oidc-demo-app/internal/handlers/common.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

136 lines
3.6 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 (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/gorilla/sessions"
"github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"code.cacert.org/cacert/oidc-demo-app/internal/models"
"code.cacert.org/cacert/oidc-demo-app/internal/services"
)
const (
oauth2RedirectStateLength = 8
sessionName = "resource_app"
)
func Authenticate(logger *log.Logger, oauth2Config *oauth2.Config, clientID string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := GetSession(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, ok := session.Values[services.SessionIDToken]; ok {
next.ServeHTTP(w, r)
return
}
session.Values[services.SessionRedirectTarget] = r.URL.String()
if err = session.Save(r, w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var authURL *url.URL
if authURL, err = url.Parse(oauth2Config.Endpoint.AuthURL); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
queryValues := authURL.Query()
queryValues.Set("client_id", clientID)
queryValues.Set("response_type", "code")
queryValues.Set("scope", "openid profile email cacert_groups")
queryValues.Set("state", base64.URLEncoding.EncodeToString(services.GenerateKey(oauth2RedirectStateLength)))
queryValues.Set("claims", getRequestedClaims(logger))
authURL.RawQuery = queryValues.Encode()
w.Header().Set("Location", authURL.String())
w.WriteHeader(http.StatusFound)
})
}
}
func getRequestedClaims(logger *log.Logger) string {
claims := make(models.OIDCClaimsRequest)
claims["userinfo"] = make(models.ClaimElement)
essentialItem := make(models.IndividualClaimRequest)
essentialItem["essential"] = true
claims["userinfo"]["https://auth.cacert.org/groups"] = &essentialItem
target := make([]byte, 0)
buf := bytes.NewBuffer(target)
enc := json.NewEncoder(buf)
if err := enc.Encode(claims); err != nil {
logger.WithError(err).Warn("could not encode claims request parameter")
}
return buf.String()
}
func GetSession(r *http.Request) (*sessions.Session, error) {
session, err := services.GetSessionStore().Get(r, sessionName)
if err != nil {
return nil, fmt.Errorf("could not get session")
}
return session, nil
}
type I18NHandler interface {
GetBundle() *i18n.Bundle
GetCatalog() *services.MessageCatalog
}
func GetLocalizer(h I18NHandler, r *http.Request) *i18n.Localizer {
accept := r.Header.Get("Accept-Language")
localizer := i18n.NewLocalizer(h.GetBundle(), accept)
return localizer
}
func BaseTemplateData(h I18NHandler, localizer *i18n.Localizer) map[string]interface{} {
msg := h.GetCatalog().LookupMessage
data := map[string]interface{}{
"WelcomeNavLabel": msg("IndexNavLabel", nil, localizer),
"ProtectedNavLabel": msg("ProtectedNavLabel", nil, localizer),
}
return data
}