Use oauth2.AuthCodeURL to simplify Authenticate

main
Jan Dittberner 9 months ago
parent 7ec9e393e0
commit 815c8e792a

@ -140,7 +140,7 @@ func main() {
sessionPath, sessionAuthKey, sessionEncKey := configureSessionParameters(config)
services.InitSessionStore(logger, sessionPath, sessionAuthKey, sessionEncKey)
authMiddleware := handlers.Authenticate(logger, oidcInfo.OAuth2Config, oidcClientID)
authMiddleware := handlers.Authenticate(oidcInfo.OAuth2Config)
publicURL := buildPublicURL(config.MustString("server.name"), config.MustInt("server.port"))

@ -18,19 +18,14 @@ 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"
)
@ -39,7 +34,7 @@ const (
sessionName = "resource_app"
)
func Authenticate(logger *log.Logger, oauth2Config *oauth2.Config, clientID string) func(http.Handler) http.Handler {
func Authenticate(oauth2Config *oauth2.Config) 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)
@ -63,28 +58,17 @@ func Authenticate(logger *log.Logger, oauth2Config *oauth2.Config, clientID stri
return
}
var authURL *url.URL
authURL := oauth2Config.AuthCodeURL(
base64.URLEncoding.EncodeToString(services.GenerateKey(oauth2RedirectStateLength)),
)
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.Header().Set("Location", authURL)
w.WriteHeader(http.StatusFound)
})
}
}
/*
func getRequestedClaims(logger *log.Logger) string {
claims := make(models.OIDCClaimsRequest)
claims["userinfo"] = make(models.ClaimElement)
@ -102,6 +86,7 @@ func getRequestedClaims(logger *log.Logger) string {
return buf.String()
}
*/
func GetSession(r *http.Request) (*sessions.Session, error) {
session, err := services.GetSessionStore().Get(r, sessionName)

@ -104,7 +104,7 @@ func DiscoverOIDC(logger *log.Logger, params *OidcParams) (*OIDCInformation, err
AuthURL: discoveryResponse.AuthorizationEndpoint,
TokenURL: discoveryResponse.TokenEndpoint,
},
Scopes: []string{"openid", "offline"},
Scopes: []string{"openid", "email", "profile"},
}
const jwkFetchTimeout = 10 * time.Second

Loading…
Cancel
Save