| 1 |
package op |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
_ "embed" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"html/template" |
| 10 |
"log/slog" |
| 11 |
"net" |
| 12 |
"net/http" |
| 13 |
"net/url" |
| 14 |
"slices" |
| 15 |
"strings" |
| 16 |
"time" |
| 17 |
|
| 18 |
"github.com/bmatcuk/doublestar/v4" |
| 19 |
httphelper "github.com/zitadel/oidc/v3/pkg/http" |
| 20 |
"github.com/zitadel/oidc/v3/pkg/oidc" |
| 21 |
) |
| 22 |
|
| 23 |
type AuthRequest interface { |
| 24 |
GetID() string |
| 25 |
GetACR() string |
| 26 |
GetAMR() []string |
| 27 |
GetAudience() []string |
| 28 |
GetAuthTime() time.Time |
| 29 |
GetClientID() string |
| 30 |
GetCodeChallenge() *oidc.CodeChallenge |
| 31 |
GetNonce() string |
| 32 |
GetRedirectURI() string |
| 33 |
GetResponseType() oidc.ResponseType |
| 34 |
GetResponseMode() oidc.ResponseMode |
| 35 |
GetScopes() []string |
| 36 |
GetState() string |
| 37 |
GetSubject() string |
| 38 |
Done() bool |
| 39 |
} |
| 40 |
|
| 41 |
// AuthRequestSessionState should be implemented if [OpenID Connect Session Management](https://openid.net/specs/openid-connect-session-1_0.html) is supported |
| 42 |
type AuthRequestSessionState interface { |
| 43 |
// GetSessionState returns session_state. |
| 44 |
// session_state is related to OpenID Connect Session Management. |
| 45 |
GetSessionState() string |
| 46 |
} |
| 47 |
|
| 48 |
type Authorizer interface { |
| 49 |
Storage() Storage |
| 50 |
Decoder() httphelper.Decoder |
| 51 |
Encoder() httphelper.Encoder |
| 52 |
IDTokenHintVerifier(context.Context) *IDTokenHintVerifier |
| 53 |
Crypto() Crypto |
| 54 |
RequestObjectSupported() bool |
| 55 |
// Deprecated: configure logging with slog.SetDefault. |
| 56 |
Logger() *slog.Logger |
| 57 |
} |
| 58 |
|
| 59 |
// AuthorizeValidator is an extension of Authorizer interface |
| 60 |
// implementing its own validation mechanism for the auth request |
| 61 |
type AuthorizeValidator interface { |
| 62 |
Authorizer |
| 63 |
ValidateAuthRequest(context.Context, *oidc.AuthRequest, Storage, *IDTokenHintVerifier) (string, error) |
| 64 |
} |
| 65 |
|
| 66 |
type CodeResponseType struct { |
| 67 |
Code string `schema:"code"` |
| 68 |
State string `schema:"state,omitempty"` |
| 69 |
SessionState string `schema:"session_state,omitempty"` |
| 70 |
} |
| 71 |
|
| 72 |
func authorizeHandler(authorizer Authorizer) func(http.ResponseWriter, *http.Request) { |
| 73 |
return func(w http.ResponseWriter, r *http.Request) { |
| 74 |
Authorize(w, r, authorizer) |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
func AuthorizeCallbackHandler(authorizer Authorizer) func(http.ResponseWriter, *http.Request) { |
| 79 |
return func(w http.ResponseWriter, r *http.Request) { |
| 80 |
AuthorizeCallback(w, r, authorizer) |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
// Authorize handles the authorization request, including |
| 85 |
// parsing, validating, storing and finally redirecting to the login handler |
| 86 |
func Authorize(w http.ResponseWriter, r *http.Request, authorizer Authorizer) { |
| 87 |
ctx, span := Tracer.Start(r.Context(), "Authorize") |
| 88 |
r = r.WithContext(ctx) |
| 89 |
defer span.End() |
| 90 |
|
| 91 |
authReq, err := ParseAuthorizeRequest(r, authorizer.Decoder()) |
| 92 |
if err != nil { |
| 93 |
AuthRequestError(w, r, nil, err, authorizer) |
| 94 |
return |
| 95 |
} |
| 96 |
if authReq.RequestParam != "" && authorizer.RequestObjectSupported() { |
| 97 |
err = ParseRequestObject(ctx, authReq, authorizer.Storage(), IssuerFromContext(ctx)) |
| 98 |
if err != nil { |
| 99 |
AuthRequestError(w, r, nil, err, authorizer) |
| 100 |
return |
| 101 |
} |
| 102 |
} |
| 103 |
if authReq.ClientID == "" { |
| 104 |
AuthRequestError(w, r, nil, fmt.Errorf("auth request is missing client_id"), authorizer) |
| 105 |
return |
| 106 |
} |
| 107 |
if authReq.RedirectURI == "" { |
| 108 |
AuthRequestError(w, r, nil, fmt.Errorf("auth request is missing redirect_uri"), authorizer) |
| 109 |
return |
| 110 |
} |
| 111 |
|
| 112 |
var client Client |
| 113 |
validation := func(ctx context.Context, authReq *oidc.AuthRequest, storage Storage, verifier *IDTokenHintVerifier) (sub string, err error) { |
| 114 |
client, err = authorizer.Storage().GetClientByClientID(ctx, authReq.ClientID) |
| 115 |
if err != nil { |
| 116 |
return "", oidc.ErrInvalidRequestRedirectURI().WithDescription("unable to retrieve client by id").WithParent(err) |
| 117 |
} |
| 118 |
return ValidateAuthRequestClient(ctx, authReq, client, verifier) |
| 119 |
} |
| 120 |
if validator, ok := authorizer.(AuthorizeValidator); ok { |
| 121 |
validation = validator.ValidateAuthRequest |
| 122 |
} |
| 123 |
userID, err := validation(ctx, authReq, authorizer.Storage(), authorizer.IDTokenHintVerifier(ctx)) |
| 124 |
if err != nil { |
| 125 |
AuthRequestError(w, r, authReq, err, authorizer) |
| 126 |
return |
| 127 |
} |
| 128 |
if authReq.RequestParam != "" { |
| 129 |
AuthRequestError(w, r, authReq, oidc.ErrRequestNotSupported(), authorizer) |
| 130 |
return |
| 131 |
} |
| 132 |
// A custom AuthorizeValidator (see the AuthorizeValidator interface) replaces the |
| 133 |
// default validation closure that assigns client above, so client may still be nil |
| 134 |
// here. RedirectToLogin dereferences client (client.LoginURL), so fetch it if a |
| 135 |
// custom validator left it unset, to avoid a nil pointer panic. |
| 136 |
if client == nil { |
| 137 |
client, err = authorizer.Storage().GetClientByClientID(ctx, authReq.ClientID) |
| 138 |
if err != nil { |
| 139 |
// The library cannot assume the custom validator verified the redirect_uri |
| 140 |
// against the client, so disable the error redirect to avoid an open redirect. |
| 141 |
AuthRequestError(w, r, authReq, oidc.ErrInvalidRequestRedirectURI().WithDescription("unable to retrieve client by id").WithParent(err), authorizer) |
| 142 |
return |
| 143 |
} |
| 144 |
} |
| 145 |
req, err := authorizer.Storage().CreateAuthRequest(ctx, authReq, userID) |
| 146 |
if err != nil { |
| 147 |
AuthRequestError(w, r, authReq, oidc.DefaultToServerError(err, "unable to save auth request"), authorizer) |
| 148 |
return |
| 149 |
} |
| 150 |
RedirectToLogin(req.GetID(), client, w, r) |
| 151 |
} |
| 152 |
|
| 153 |
// ParseAuthorizeRequest parsed the http request into an oidc.AuthRequest |
| 154 |
func ParseAuthorizeRequest(r *http.Request, decoder httphelper.Decoder) (*oidc.AuthRequest, error) { |
| 155 |
err := r.ParseForm() |
| 156 |
if err != nil { |
| 157 |
return nil, oidc.ErrInvalidRequest().WithDescription("cannot parse form").WithParent(err) |
| 158 |
} |
| 159 |
authReq := new(oidc.AuthRequest) |
| 160 |
err = decoder.Decode(authReq, r.Form) |
| 161 |
if err != nil { |
| 162 |
return nil, oidc.ErrInvalidRequest().WithDescription("cannot parse auth request").WithParent(err) |
| 163 |
} |
| 164 |
return authReq, nil |
| 165 |
} |
| 166 |
|
| 167 |
// ParseRequestObject parse the `request` parameter, validates the token including the signature |
| 168 |
// and copies the token claims into the auth request |
| 169 |
func ParseRequestObject(ctx context.Context, authReq *oidc.AuthRequest, storage Storage, issuer string) error { |
| 170 |
requestObject := new(oidc.RequestObject) |
| 171 |
payload, err := oidc.ParseToken(authReq.RequestParam, requestObject) |
| 172 |
if err != nil { |
| 173 |
return err |
| 174 |
} |
| 175 |
|
| 176 |
if requestObject.ClientID != "" && requestObject.ClientID != authReq.ClientID { |
| 177 |
return oidc.ErrInvalidRequest().WithDescription("missing or wrong client id in request") |
| 178 |
} |
| 179 |
if requestObject.ResponseType != "" && requestObject.ResponseType != authReq.ResponseType { |
| 180 |
return oidc.ErrInvalidRequest().WithDescription("missing or wrong response type in request") |
| 181 |
} |
| 182 |
if requestObject.Issuer != requestObject.ClientID { |
| 183 |
return oidc.ErrInvalidRequest().WithDescription("missing or wrong issuer in request") |
| 184 |
} |
| 185 |
if !slices.Contains(requestObject.Audience, issuer) { |
| 186 |
return oidc.ErrInvalidRequest().WithDescription("issuer missing in audience") |
| 187 |
} |
| 188 |
keySet := &jwtProfileKeySet{storage: storage, clientID: requestObject.Issuer} |
| 189 |
if err = oidc.CheckSignature(ctx, authReq.RequestParam, payload, requestObject, nil, keySet); err != nil { |
| 190 |
return oidc.ErrInvalidRequest().WithParent(err).WithDescription("invalid request signature") |
| 191 |
} |
| 192 |
CopyRequestObjectToAuthRequest(authReq, requestObject) |
| 193 |
return nil |
| 194 |
} |
| 195 |
|
| 196 |
// CopyRequestObjectToAuthRequest overwrites present values from the Request Object into the auth request |
| 197 |
// and clears the `RequestParam` of the auth request |
| 198 |
func CopyRequestObjectToAuthRequest(authReq *oidc.AuthRequest, requestObject *oidc.RequestObject) { |
| 199 |
if slices.Contains(authReq.Scopes, oidc.ScopeOpenID) && len(requestObject.Scopes) > 0 { |
| 200 |
authReq.Scopes = requestObject.Scopes |
| 201 |
} |
| 202 |
if requestObject.RedirectURI != "" { |
| 203 |
authReq.RedirectURI = requestObject.RedirectURI |
| 204 |
} |
| 205 |
if requestObject.State != "" { |
| 206 |
authReq.State = requestObject.State |
| 207 |
} |
| 208 |
if requestObject.ResponseMode != "" { |
| 209 |
authReq.ResponseMode = requestObject.ResponseMode |
| 210 |
} |
| 211 |
if requestObject.Nonce != "" { |
| 212 |
authReq.Nonce = requestObject.Nonce |
| 213 |
} |
| 214 |
if requestObject.Display != "" { |
| 215 |
authReq.Display = requestObject.Display |
| 216 |
} |
| 217 |
if len(requestObject.Prompt) > 0 { |
| 218 |
authReq.Prompt = requestObject.Prompt |
| 219 |
} |
| 220 |
if requestObject.MaxAge != nil { |
| 221 |
authReq.MaxAge = requestObject.MaxAge |
| 222 |
} |
| 223 |
if len(requestObject.UILocales) > 0 { |
| 224 |
authReq.UILocales = requestObject.UILocales |
| 225 |
} |
| 226 |
if requestObject.IDTokenHint != "" { |
| 227 |
authReq.IDTokenHint = requestObject.IDTokenHint |
| 228 |
} |
| 229 |
if requestObject.LoginHint != "" { |
| 230 |
authReq.LoginHint = requestObject.LoginHint |
| 231 |
} |
| 232 |
if len(requestObject.ACRValues) > 0 { |
| 233 |
authReq.ACRValues = requestObject.ACRValues |
| 234 |
} |
| 235 |
if requestObject.CodeChallenge != "" { |
| 236 |
authReq.CodeChallenge = requestObject.CodeChallenge |
| 237 |
} |
| 238 |
if requestObject.CodeChallengeMethod != "" { |
| 239 |
authReq.CodeChallengeMethod = requestObject.CodeChallengeMethod |
| 240 |
} |
| 241 |
authReq.RequestParam = "" |
| 242 |
} |
| 243 |
|
| 244 |
// ValidateAuthRequest validates the authorize parameters and returns the userID of the id_token_hint if passed. |
| 245 |
// |
| 246 |
// Deprecated: Use [ValidateAuthRequestClient] to prevent querying for the Client twice. |
| 247 |
func ValidateAuthRequest(ctx context.Context, authReq *oidc.AuthRequest, storage Storage, verifier *IDTokenHintVerifier) (sub string, err error) { |
| 248 |
ctx, span := Tracer.Start(ctx, "ValidateAuthRequest") |
| 249 |
defer span.End() |
| 250 |
|
| 251 |
client, err := storage.GetClientByClientID(ctx, authReq.ClientID) |
| 252 |
if err != nil { |
| 253 |
return "", oidc.ErrInvalidRequestRedirectURI().WithDescription("unable to retrieve client by id").WithParent(err) |
| 254 |
} |
| 255 |
return ValidateAuthRequestClient(ctx, authReq, client, verifier) |
| 256 |
} |
| 257 |
|
| 258 |
// ValidateAuthRequestClient validates the Auth request against the passed client. |
| 259 |
// If id_token_hint is part of the request, the subject of the token is returned. |
| 260 |
func ValidateAuthRequestClient(ctx context.Context, authReq *oidc.AuthRequest, client Client, verifier *IDTokenHintVerifier) (sub string, err error) { |
| 261 |
ctx, span := Tracer.Start(ctx, "ValidateAuthRequestClient") |
| 262 |
defer span.End() |
| 263 |
|
| 264 |
if err := ValidateAuthReqRedirectURI(client, authReq.RedirectURI, authReq.ResponseType); err != nil { |
| 265 |
return "", err |
| 266 |
} |
| 267 |
authReq.MaxAge, err = ValidateAuthReqPrompt(authReq.Prompt, authReq.MaxAge) |
| 268 |
if err != nil { |
| 269 |
return "", err |
| 270 |
} |
| 271 |
authReq.Scopes, err = ValidateAuthReqScopes(client, authReq.Scopes) |
| 272 |
if err != nil { |
| 273 |
return "", err |
| 274 |
} |
| 275 |
if err := ValidateAuthReqResponseType(client, authReq.ResponseType); err != nil { |
| 276 |
return "", err |
| 277 |
} |
| 278 |
return ValidateAuthReqIDTokenHint(ctx, authReq.IDTokenHint, verifier) |
| 279 |
} |
| 280 |
|
| 281 |
// ValidateAuthReqPrompt validates the passed prompt values and sets max_age to 0 if prompt login is present |
| 282 |
func ValidateAuthReqPrompt(prompts []string, maxAge *uint) (_ *uint, err error) { |
| 283 |
for _, prompt := range prompts { |
| 284 |
if prompt == oidc.PromptNone && len(prompts) > 1 { |
| 285 |
return nil, oidc.ErrInvalidRequest().WithDescription("The prompt parameter `none` must only be used as a single value") |
| 286 |
} |
| 287 |
if prompt == oidc.PromptLogin { |
| 288 |
maxAge = oidc.NewMaxAge(0) |
| 289 |
} |
| 290 |
} |
| 291 |
return maxAge, nil |
| 292 |
} |
| 293 |
|
| 294 |
// ValidateAuthReqScopes validates the passed scopes and deletes any unsupported scopes. |
| 295 |
// An error is returned if scopes is empty. |
| 296 |
func ValidateAuthReqScopes(client Client, scopes []string) ([]string, error) { |
| 297 |
if len(scopes) == 0 { |
| 298 |
return nil, oidc.ErrInvalidRequest(). |
| 299 |
WithDescription("The scope of your request is missing. Please ensure some scopes are requested. " + |
| 300 |
"If you have any questions, you may contact the administrator of the application.") |
| 301 |
} |
| 302 |
scopes = slices.DeleteFunc(scopes, func(scope string) bool { |
| 303 |
return !(scope == oidc.ScopeOpenID || |
| 304 |
scope == oidc.ScopeProfile || |
| 305 |
scope == oidc.ScopeEmail || |
| 306 |
scope == oidc.ScopePhone || |
| 307 |
scope == oidc.ScopeAddress || |
| 308 |
scope == oidc.ScopeOfflineAccess) && |
| 309 |
!client.IsScopeAllowed(scope) |
| 310 |
}) |
| 311 |
return scopes, nil |
| 312 |
} |
| 313 |
|
| 314 |
// checkURIAgainstRedirects just checks against the valid redirect URIs and ignores |
| 315 |
// other factors. |
| 316 |
func checkURIAgainstRedirects(client Client, uri string) error { |
| 317 |
if slices.Contains(client.RedirectURIs(), uri) { |
| 318 |
return nil |
| 319 |
} |
| 320 |
if globClient, ok := client.(HasRedirectGlobs); ok { |
| 321 |
for _, uriGlob := range globClient.RedirectURIGlobs() { |
| 322 |
isMatch, err := doublestar.Match(uriGlob, uri) |
| 323 |
if err != nil { |
| 324 |
return oidc.ErrServerError().WithParent(err) |
| 325 |
} |
| 326 |
if isMatch { |
| 327 |
return nil |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
return oidc.ErrInvalidRequestRedirectURI(). |
| 332 |
WithDescription("The requested redirect_uri is missing in the client configuration. " + |
| 333 |
"If you have any questions, you may contact the administrator of the application.") |
| 334 |
} |
| 335 |
|
| 336 |
// ValidateAuthReqRedirectURI validates the passed redirect_uri and response_type to the registered uris and client type |
| 337 |
func ValidateAuthReqRedirectURI(client Client, uri string, responseType oidc.ResponseType) error { |
| 338 |
if uri == "" { |
| 339 |
return oidc.ErrInvalidRequestRedirectURI().WithDescription("The redirect_uri is missing in the request. " + |
| 340 |
"Please ensure it is added to the request. If you have any questions, you may contact the administrator of the application.") |
| 341 |
} |
| 342 |
if client.ApplicationType() == ApplicationTypeNative { |
| 343 |
return validateAuthReqRedirectURINative(client, uri) |
| 344 |
} |
| 345 |
if strings.HasPrefix(uri, "https://") { |
| 346 |
return checkURIAgainstRedirects(client, uri) |
| 347 |
} |
| 348 |
if err := checkURIAgainstRedirects(client, uri); err != nil { |
| 349 |
return err |
| 350 |
} |
| 351 |
if strings.HasPrefix(uri, "http://") { |
| 352 |
if client.DevMode() { |
| 353 |
return nil |
| 354 |
} |
| 355 |
if responseType == oidc.ResponseTypeCode && IsConfidentialType(client) { |
| 356 |
return nil |
| 357 |
} |
| 358 |
return oidc.ErrInvalidRequestRedirectURI().WithDescription("This client's redirect_uri is http and is not allowed. " + |
| 359 |
"If you have any questions, you may contact the administrator of the application.") |
| 360 |
} |
| 361 |
return oidc.ErrInvalidRequestRedirectURI().WithDescription("This client's redirect_uri is using a custom schema and is not allowed. " + |
| 362 |
"If you have any questions, you may contact the administrator of the application.") |
| 363 |
} |
| 364 |
|
| 365 |
// ValidateAuthReqRedirectURINative validates the passed redirect_uri and response_type to the registered uris and client type |
| 366 |
func validateAuthReqRedirectURINative(client Client, uri string) error { |
| 367 |
parsedURL, isLoopback := HTTPLoopbackOrLocalhost(uri) |
| 368 |
isCustomSchema := !(strings.HasPrefix(uri, "http://") || strings.HasPrefix(uri, "https://")) |
| 369 |
if err := checkURIAgainstRedirects(client, uri); err == nil { |
| 370 |
if client.DevMode() { |
| 371 |
return nil |
| 372 |
} |
| 373 |
if !isLoopback && strings.HasPrefix(uri, "https://") { |
| 374 |
return nil |
| 375 |
} |
| 376 |
// The RedirectURIs are only valid for native clients when localhost or non-"http://" and "https://" |
| 377 |
if isLoopback || isCustomSchema { |
| 378 |
return nil |
| 379 |
} |
| 380 |
return oidc.ErrInvalidRequestRedirectURI().WithDescription("This client's redirect_uri is http and is not allowed. " + |
| 381 |
"If you have any questions, you may contact the administrator of the application.") |
| 382 |
} |
| 383 |
if !isLoopback { |
| 384 |
return oidc.ErrInvalidRequestRedirectURI().WithDescription("The requested redirect_uri is missing in the client configuration. " + |
| 385 |
"If you have any questions, you may contact the administrator of the application.") |
| 386 |
} |
| 387 |
for _, uri := range client.RedirectURIs() { |
| 388 |
redirectURI, ok := HTTPLoopbackOrLocalhost(uri) |
| 389 |
if ok && equalURI(parsedURL, redirectURI) { |
| 390 |
return nil |
| 391 |
} |
| 392 |
} |
| 393 |
return oidc.ErrInvalidRequestRedirectURI().WithDescription("The requested redirect_uri is missing in the client configuration." + |
| 394 |
" If you have any questions, you may contact the administrator of the application.") |
| 395 |
} |
| 396 |
|
| 397 |
func equalURI(url1, url2 *url.URL) bool { |
| 398 |
return url1.Path == url2.Path && url1.RawQuery == url2.RawQuery |
| 399 |
} |
| 400 |
|
| 401 |
func HTTPLoopbackOrLocalhost(rawURL string) (*url.URL, bool) { |
| 402 |
parsedURL, err := url.Parse(rawURL) |
| 403 |
if err != nil { |
| 404 |
return nil, false |
| 405 |
} |
| 406 |
if parsedURL.Scheme == "http" || parsedURL.Scheme == "https" { |
| 407 |
hostName := parsedURL.Hostname() |
| 408 |
return parsedURL, hostName == "localhost" || net.ParseIP(hostName).IsLoopback() |
| 409 |
} |
| 410 |
return nil, false |
| 411 |
} |
| 412 |
|
| 413 |
// ValidateAuthReqResponseType validates the passed response_type to the registered response types |
| 414 |
func ValidateAuthReqResponseType(client Client, responseType oidc.ResponseType) error { |
| 415 |
if responseType == "" { |
| 416 |
return oidc.ErrInvalidRequest().WithDescription("The response type is missing in your request. " + |
| 417 |
"If you have any questions, you may contact the administrator of the application.") |
| 418 |
} |
| 419 |
if !ContainsResponseType(client.ResponseTypes(), responseType) { |
| 420 |
return oidc.ErrUnauthorizedClient().WithDescription("The requested response type is missing in the client configuration. " + |
| 421 |
"If you have any questions, you may contact the administrator of the application.") |
| 422 |
} |
| 423 |
return nil |
| 424 |
} |
| 425 |
|
| 426 |
// ValidateAuthReqIDTokenHint validates the id_token_hint (if passed as parameter in the request) |
| 427 |
// and returns the `sub` claim |
| 428 |
func ValidateAuthReqIDTokenHint(ctx context.Context, idTokenHint string, verifier *IDTokenHintVerifier) (string, error) { |
| 429 |
if idTokenHint == "" { |
| 430 |
return "", nil |
| 431 |
} |
| 432 |
claims, err := VerifyIDTokenHint[*oidc.TokenClaims](ctx, idTokenHint, verifier) |
| 433 |
if err != nil && !errors.As(err, &IDTokenHintExpiredError{}) { |
| 434 |
return "", oidc.ErrLoginRequired().WithDescription("The id_token_hint is invalid. " + |
| 435 |
"If you have any questions, you may contact the administrator of the application.").WithParent(err) |
| 436 |
} |
| 437 |
return claims.GetSubject(), nil |
| 438 |
} |
| 439 |
|
| 440 |
// RedirectToLogin redirects the end user to the Login UI for authentication |
| 441 |
func RedirectToLogin(authReqID string, client Client, w http.ResponseWriter, r *http.Request) { |
| 442 |
login := client.LoginURL(authReqID) |
| 443 |
http.Redirect(w, r, login, http.StatusFound) |
| 444 |
} |
| 445 |
|
| 446 |
// AuthorizeCallback handles the callback after authentication in the Login UI |
| 447 |
func AuthorizeCallback(w http.ResponseWriter, r *http.Request, authorizer Authorizer) { |
| 448 |
ctx, span := Tracer.Start(r.Context(), "AuthorizeCallback") |
| 449 |
r = r.WithContext(ctx) |
| 450 |
defer span.End() |
| 451 |
|
| 452 |
id, err := ParseAuthorizeCallbackRequest(r) |
| 453 |
if err != nil { |
| 454 |
AuthRequestError(w, r, nil, err, authorizer) |
| 455 |
return |
| 456 |
} |
| 457 |
authReq, err := authorizer.Storage().AuthRequestByID(r.Context(), id) |
| 458 |
if err != nil { |
| 459 |
AuthRequestError(w, r, nil, err, authorizer) |
| 460 |
return |
| 461 |
} |
| 462 |
if !authReq.Done() { |
| 463 |
AuthRequestError(w, r, authReq, |
| 464 |
oidc.ErrInteractionRequired().WithDescription("Unfortunately, the user may be not logged in and/or additional interaction is required."), |
| 465 |
authorizer) |
| 466 |
return |
| 467 |
} |
| 468 |
AuthResponse(authReq, authorizer, w, r) |
| 469 |
} |
| 470 |
|
| 471 |
func ParseAuthorizeCallbackRequest(r *http.Request) (id string, err error) { |
| 472 |
if err = r.ParseForm(); err != nil { |
| 473 |
return "", fmt.Errorf("cannot parse form: %w", err) |
| 474 |
} |
| 475 |
id = r.Form.Get("id") |
| 476 |
if id == "" { |
| 477 |
return "", errors.New("auth request callback is missing id") |
| 478 |
} |
| 479 |
return id, nil |
| 480 |
} |
| 481 |
|
| 482 |
// AuthResponse creates the successful authentication response (either code or tokens) |
| 483 |
func AuthResponse(authReq AuthRequest, authorizer Authorizer, w http.ResponseWriter, r *http.Request) { |
| 484 |
ctx, span := Tracer.Start(r.Context(), "AuthResponse") |
| 485 |
r = r.WithContext(ctx) |
| 486 |
defer span.End() |
| 487 |
|
| 488 |
client, err := authorizer.Storage().GetClientByClientID(r.Context(), authReq.GetClientID()) |
| 489 |
if err != nil { |
| 490 |
AuthRequestError(w, r, authReq, err, authorizer) |
| 491 |
return |
| 492 |
} |
| 493 |
if authReq.GetResponseType() == oidc.ResponseTypeCode { |
| 494 |
AuthResponseCode(w, r, authReq, authorizer) |
| 495 |
return |
| 496 |
} |
| 497 |
AuthResponseToken(w, r, authReq, authorizer, client) |
| 498 |
} |
| 499 |
|
| 500 |
// AuthResponseCode handles the creation of a successful authentication response using an authorization code |
| 501 |
func AuthResponseCode(w http.ResponseWriter, r *http.Request, authReq AuthRequest, authorizer Authorizer) { |
| 502 |
ctx, span := Tracer.Start(r.Context(), "AuthResponseCode") |
| 503 |
defer span.End() |
| 504 |
r = r.WithContext(ctx) |
| 505 |
|
| 506 |
var err error |
| 507 |
if authReq.GetResponseMode() == oidc.ResponseModeFormPost { |
| 508 |
err = handleFormPostResponse(w, r, authReq, authorizer) |
| 509 |
} else { |
| 510 |
err = handleRedirectResponse(w, r, authReq, authorizer) |
| 511 |
} |
| 512 |
|
| 513 |
if err != nil { |
| 514 |
AuthRequestError(w, r, authReq, err, authorizer) |
| 515 |
} |
| 516 |
} |
| 517 |
|
| 518 |
// handleFormPostResponse processes the authentication response using form post method |
| 519 |
func handleFormPostResponse(w http.ResponseWriter, r *http.Request, authReq AuthRequest, authorizer Authorizer) error { |
| 520 |
codeResponse, err := BuildAuthResponseCodeResponsePayload(r.Context(), authReq, authorizer) |
| 521 |
if err != nil { |
| 522 |
return err |
| 523 |
} |
| 524 |
return AuthResponseFormPost(w, authReq.GetRedirectURI(), codeResponse, authorizer.Encoder()) |
| 525 |
} |
| 526 |
|
| 527 |
// handleRedirectResponse processes the authentication response using the redirect method |
| 528 |
func handleRedirectResponse(w http.ResponseWriter, r *http.Request, authReq AuthRequest, authorizer Authorizer) error { |
| 529 |
callbackURL, err := BuildAuthResponseCallbackURL(r.Context(), authReq, authorizer) |
| 530 |
if err != nil { |
| 531 |
return err |
| 532 |
} |
| 533 |
http.Redirect(w, r, callbackURL, http.StatusFound) |
| 534 |
return nil |
| 535 |
} |
| 536 |
|
| 537 |
// BuildAuthResponseCodeResponsePayload generates the authorization code response payload for the authentication request |
| 538 |
func BuildAuthResponseCodeResponsePayload(ctx context.Context, authReq AuthRequest, authorizer Authorizer) (*CodeResponseType, error) { |
| 539 |
code, err := CreateAuthRequestCode(ctx, authReq, authorizer.Storage(), authorizer.Crypto()) |
| 540 |
if err != nil { |
| 541 |
return nil, err |
| 542 |
} |
| 543 |
|
| 544 |
sessionState := "" |
| 545 |
if authRequestSessionState, ok := authReq.(AuthRequestSessionState); ok { |
| 546 |
sessionState = authRequestSessionState.GetSessionState() |
| 547 |
} |
| 548 |
|
| 549 |
return &CodeResponseType{ |
| 550 |
Code: code, |
| 551 |
State: authReq.GetState(), |
| 552 |
SessionState: sessionState, |
| 553 |
}, nil |
| 554 |
} |
| 555 |
|
| 556 |
// BuildAuthResponseCallbackURL generates the callback URL for a successful authorization code response |
| 557 |
func BuildAuthResponseCallbackURL(ctx context.Context, authReq AuthRequest, authorizer Authorizer) (string, error) { |
| 558 |
codeResponse, err := BuildAuthResponseCodeResponsePayload(ctx, authReq, authorizer) |
| 559 |
if err != nil { |
| 560 |
return "", err |
| 561 |
} |
| 562 |
|
| 563 |
return AuthResponseURL(authReq.GetRedirectURI(), authReq.GetResponseType(), authReq.GetResponseMode(), codeResponse, authorizer.Encoder()) |
| 564 |
} |
| 565 |
|
| 566 |
// AuthResponseToken creates the successful token(s) authentication response |
| 567 |
func AuthResponseToken(w http.ResponseWriter, r *http.Request, authReq AuthRequest, authorizer Authorizer, client Client) { |
| 568 |
ctx, span := Tracer.Start(r.Context(), "AuthResponseToken") |
| 569 |
defer span.End() |
| 570 |
r = r.WithContext(ctx) |
| 571 |
|
| 572 |
createAccessToken := authReq.GetResponseType() != oidc.ResponseTypeIDTokenOnly |
| 573 |
resp, err := CreateTokenResponse(r.Context(), authReq, client, authorizer, createAccessToken, "", "") |
| 574 |
if err != nil { |
| 575 |
AuthRequestError(w, r, authReq, err, authorizer) |
| 576 |
return |
| 577 |
} |
| 578 |
|
| 579 |
if authReq.GetResponseMode() == oidc.ResponseModeFormPost { |
| 580 |
err := AuthResponseFormPost(w, authReq.GetRedirectURI(), resp, authorizer.Encoder()) |
| 581 |
if err != nil { |
| 582 |
AuthRequestError(w, r, authReq, err, authorizer) |
| 583 |
return |
| 584 |
} |
| 585 |
|
| 586 |
return |
| 587 |
} |
| 588 |
|
| 589 |
callback, err := AuthResponseURL(authReq.GetRedirectURI(), authReq.GetResponseType(), authReq.GetResponseMode(), resp, authorizer.Encoder()) |
| 590 |
if err != nil { |
| 591 |
AuthRequestError(w, r, authReq, err, authorizer) |
| 592 |
return |
| 593 |
} |
| 594 |
http.Redirect(w, r, callback, http.StatusFound) |
| 595 |
} |
| 596 |
|
| 597 |
// CreateAuthRequestCode creates and stores a code for the auth code response |
| 598 |
func CreateAuthRequestCode(ctx context.Context, authReq AuthRequest, storage Storage, encrypter Encrypter) (string, error) { |
| 599 |
ctx, span := Tracer.Start(ctx, "CreateAuthRequestCode") |
| 600 |
defer span.End() |
| 601 |
|
| 602 |
code, err := BuildAuthRequestCode(authReq, encrypter) |
| 603 |
if err != nil { |
| 604 |
return "", err |
| 605 |
} |
| 606 |
if err := storage.SaveAuthCode(ctx, authReq.GetID(), code); err != nil { |
| 607 |
return "", err |
| 608 |
} |
| 609 |
return code, nil |
| 610 |
} |
| 611 |
|
| 612 |
// BuildAuthRequestCode builds the string representation of the auth code |
| 613 |
func BuildAuthRequestCode(authReq AuthRequest, encrypter Encrypter) (string, error) { |
| 614 |
return encrypter.Encrypt(authReq.GetID()) |
| 615 |
} |
| 616 |
|
| 617 |
// AuthResponseURL encodes the authorization response (successful and error) and sets it as query or fragment values |
| 618 |
// depending on the response_mode and response_type |
| 619 |
func AuthResponseURL(redirectURI string, responseType oidc.ResponseType, responseMode oidc.ResponseMode, response any, encoder httphelper.Encoder) (string, error) { |
| 620 |
uri, err := url.Parse(redirectURI) |
| 621 |
if err != nil { |
| 622 |
return "", oidc.ErrServerError().WithParent(err) |
| 623 |
} |
| 624 |
params, err := httphelper.URLEncodeParams(response, encoder) |
| 625 |
if err != nil { |
| 626 |
return "", oidc.ErrServerError().WithParent(err) |
| 627 |
} |
| 628 |
// return explicitly requested mode |
| 629 |
if responseMode == oidc.ResponseModeQuery { |
| 630 |
return mergeQueryParams(uri, params), nil |
| 631 |
} |
| 632 |
if responseMode == oidc.ResponseModeFragment { |
| 633 |
return setFragment(uri, params), nil |
| 634 |
} |
| 635 |
// implicit must use fragment mode is not specified by client |
| 636 |
if responseType == oidc.ResponseTypeIDToken || responseType == oidc.ResponseTypeIDTokenOnly { |
| 637 |
return setFragment(uri, params), nil |
| 638 |
} |
| 639 |
// if we get here it's code flow: defaults to query |
| 640 |
return mergeQueryParams(uri, params), nil |
| 641 |
} |
| 642 |
|
| 643 |
//go:embed form_post.html.tmpl |
| 644 |
var formPostHtmlTemplate string |
| 645 |
|
| 646 |
var formPostTmpl = template.Must(template.New("form_post").Parse(formPostHtmlTemplate)) |
| 647 |
|
| 648 |
// AuthResponseFormPost responds a html page that automatically submits the form which contains the auth response parameters |
| 649 |
func AuthResponseFormPost(res http.ResponseWriter, redirectURI string, response any, encoder httphelper.Encoder) error { |
| 650 |
values := make(map[string][]string) |
| 651 |
err := encoder.Encode(response, values) |
| 652 |
if err != nil { |
| 653 |
return oidc.ErrServerError().WithParent(err) |
| 654 |
} |
| 655 |
|
| 656 |
params := &struct { |
| 657 |
RedirectURI string |
| 658 |
Params any |
| 659 |
}{ |
| 660 |
RedirectURI: redirectURI, |
| 661 |
Params: values, |
| 662 |
} |
| 663 |
|
| 664 |
var buf bytes.Buffer |
| 665 |
err = formPostTmpl.Execute(&buf, params) |
| 666 |
if err != nil { |
| 667 |
return oidc.ErrServerError().WithParent(err) |
| 668 |
} |
| 669 |
|
| 670 |
res.Header().Set("Cache-Control", "no-store") |
| 671 |
res.WriteHeader(http.StatusOK) |
| 672 |
_, err = buf.WriteTo(res) |
| 673 |
if err != nil { |
| 674 |
return oidc.ErrServerError().WithParent(err) |
| 675 |
} |
| 676 |
|
| 677 |
return nil |
| 678 |
} |
| 679 |
|
| 680 |
func setFragment(uri *url.URL, params url.Values) string { |
| 681 |
uri.Fragment = params.Encode() |
| 682 |
return uri.String() |
| 683 |
} |
| 684 |
|
| 685 |
func mergeQueryParams(uri *url.URL, params url.Values) string { |
| 686 |
queries := uri.Query() |
| 687 |
for param, values := range params { |
| 688 |
for _, value := range values { |
| 689 |
queries.Add(param, value) |
| 690 |
} |
| 691 |
} |
| 692 |
uri.RawQuery = queries.Encode() |
| 693 |
return uri.String() |
| 694 |
} |