From 5ef597b1dbfb0ddd797b5ccda78edccd2f58d172 Mon Sep 17 00:00:00 2001 From: Ayato Date: Tue, 5 Mar 2024 22:04:43 +0900 Subject: [PATCH] feat(op): Add response_mode: form_post (#551) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(op): Add response_mode: form_post * Fix to parse the template ahead of time * Fix to render the template in a buffer * Remove unnecessary import * Fix test * Fix example client setting * Make sure the client not to reuse the content of the response * Fix error handling * Add the response_mode param * Allow implicit flow in the example app * feat(rp): allow form_post in code exchange callback handler --------- Co-authored-by: Tim Möhlmann --- example/client/app/app.go | 15 +++++++- example/server/storage/client.go | 4 +-- example/server/storage/oidc.go | 4 ++- pkg/client/rp/relying_party.go | 7 ++-- pkg/oidc/authorization.go | 1 + pkg/op/auth_request.go | 62 ++++++++++++++++++++++++++++++++ pkg/op/auth_request_test.go | 35 ++++++++++++++++-- pkg/op/form_post.html.tmpl | 14 ++++++++ 8 files changed, 131 insertions(+), 11 deletions(-) create mode 100644 pkg/op/form_post.html.tmpl diff --git a/example/client/app/app.go b/example/client/app/app.go index a779169..9b43b8d 100644 --- a/example/client/app/app.go +++ b/example/client/app/app.go @@ -32,6 +32,7 @@ func main() { issuer := os.Getenv("ISSUER") port := os.Getenv("PORT") scopes := strings.Split(os.Getenv("SCOPES"), " ") + responseMode := os.Getenv("RESPONSE_MODE") redirectURI := fmt.Sprintf("http://localhost:%v%v", port, callbackPath) cookieHandler := httphelper.NewCookieHandler(key, key, httphelper.WithUnsecure()) @@ -77,12 +78,24 @@ func main() { return uuid.New().String() } + urlOptions := []rp.URLParamOpt{ + rp.WithPromptURLParam("Welcome back!"), + } + + if responseMode != "" { + urlOptions = append(urlOptions, rp.WithResponseModeURLParam(oidc.ResponseMode(responseMode))) + } + // register the AuthURLHandler at your preferred path. // the AuthURLHandler creates the auth request and redirects the user to the auth server. // including state handling with secure cookie and the possibility to use PKCE. // Prompts can optionally be set to inform the server of // any messages that need to be prompted back to the user. - http.Handle("/login", rp.AuthURLHandler(state, provider, rp.WithPromptURLParam("Welcome back!"))) + http.Handle("/login", rp.AuthURLHandler( + state, + provider, + urlOptions..., + )) // for demonstration purposes the returned userinfo response is written as JSON object onto response marshalUserinfo := func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[*oidc.IDTokenClaims], state string, rp rp.RelyingParty, info *oidc.UserInfo) { diff --git a/example/server/storage/client.go b/example/server/storage/client.go index 2e57cc5..010b9ce 100644 --- a/example/server/storage/client.go +++ b/example/server/storage/client.go @@ -184,10 +184,10 @@ func WebClient(id, secret string, redirectURIs ...string) *Client { applicationType: op.ApplicationTypeWeb, authMethod: oidc.AuthMethodBasic, loginURL: defaultLoginURL, - responseTypes: []oidc.ResponseType{oidc.ResponseTypeCode}, + responseTypes: []oidc.ResponseType{oidc.ResponseTypeCode, oidc.ResponseTypeIDTokenOnly, oidc.ResponseTypeIDToken}, grantTypes: []oidc.GrantType{oidc.GrantTypeCode, oidc.GrantTypeRefreshToken, oidc.GrantTypeTokenExchange}, accessTokenType: op.AccessTokenTypeBearer, - devMode: false, + devMode: true, idTokenUserinfoClaimsAssertion: false, clockSkew: 0, } diff --git a/example/server/storage/oidc.go b/example/server/storage/oidc.go index 2509f77..9cd08d9 100644 --- a/example/server/storage/oidc.go +++ b/example/server/storage/oidc.go @@ -35,6 +35,7 @@ type AuthRequest struct { UserID string Scopes []string ResponseType oidc.ResponseType + ResponseMode oidc.ResponseMode Nonce string CodeChallenge *OIDCCodeChallenge @@ -100,7 +101,7 @@ func (a *AuthRequest) GetResponseType() oidc.ResponseType { } func (a *AuthRequest) GetResponseMode() oidc.ResponseMode { - return "" // we won't handle response mode in this example + return a.ResponseMode } func (a *AuthRequest) GetScopes() []string { @@ -154,6 +155,7 @@ func authRequestToInternal(authReq *oidc.AuthRequest, userID string) *AuthReques UserID: userID, Scopes: authReq.Scopes, ResponseType: authReq.ResponseType, + ResponseMode: authReq.ResponseMode, Nonce: authReq.Nonce, CodeChallenge: &OIDCCodeChallenge{ Challenge: authReq.CodeChallenge, diff --git a/pkg/client/rp/relying_party.go b/pkg/client/rp/relying_party.go index 72270fe..74da71e 100644 --- a/pkg/client/rp/relying_party.go +++ b/pkg/client/rp/relying_party.go @@ -494,9 +494,8 @@ func CodeExchangeHandler[C oidc.IDClaims](callback CodeExchangeCallback[C], rp R unauthorizedError(w, r, "failed to get state: "+err.Error(), state, rp) return } - params := r.URL.Query() - if params.Get("error") != "" { - rp.ErrorHandler()(w, r, params.Get("error"), params.Get("error_description"), state) + if errValue := r.FormValue("error"); errValue != "" { + rp.ErrorHandler()(w, r, errValue, r.FormValue("error_description"), state) return } codeOpts := make([]CodeExchangeOpt, len(urlParam)) @@ -521,7 +520,7 @@ func CodeExchangeHandler[C oidc.IDClaims](callback CodeExchangeCallback[C], rp R } codeOpts = append(codeOpts, WithClientAssertionJWT(assertion)) } - tokens, err := CodeExchange[C](r.Context(), params.Get("code"), rp, codeOpts...) + tokens, err := CodeExchange[C](r.Context(), r.FormValue("code"), rp, codeOpts...) if err != nil { unauthorizedError(w, r, "failed to exchange token: "+err.Error(), state, rp) return diff --git a/pkg/oidc/authorization.go b/pkg/oidc/authorization.go index 89139ba..fa37dbf 100644 --- a/pkg/oidc/authorization.go +++ b/pkg/oidc/authorization.go @@ -48,6 +48,7 @@ const ( ResponseModeQuery ResponseMode = "query" ResponseModeFragment ResponseMode = "fragment" + ResponseModeFormPost ResponseMode = "form_post" // PromptNone (`none`) disallows the Authorization Server to display any authentication or consent user interface pages. // An error (login_required, interaction_required, ...) will be returned if the user is not already authenticated or consent is needed diff --git a/pkg/op/auth_request.go b/pkg/op/auth_request.go index d570e25..18d8826 100644 --- a/pkg/op/auth_request.go +++ b/pkg/op/auth_request.go @@ -1,9 +1,12 @@ package op import ( + "bytes" "context" + _ "embed" "errors" "fmt" + "html/template" "log/slog" "net" "net/http" @@ -464,6 +467,17 @@ func AuthResponseCode(w http.ResponseWriter, r *http.Request, authReq AuthReques Code: code, State: authReq.GetState(), } + + if authReq.GetResponseMode() == oidc.ResponseModeFormPost { + err := AuthResponseFormPost(w, authReq.GetRedirectURI(), &codeResponse, authorizer.Encoder()) + if err != nil { + AuthRequestError(w, r, authReq, err, authorizer) + return + } + + return + } + callback, err := AuthResponseURL(authReq.GetRedirectURI(), authReq.GetResponseType(), authReq.GetResponseMode(), &codeResponse, authorizer.Encoder()) if err != nil { AuthRequestError(w, r, authReq, err, authorizer) @@ -484,6 +498,17 @@ func AuthResponseToken(w http.ResponseWriter, r *http.Request, authReq AuthReque AuthRequestError(w, r, authReq, err, authorizer) return } + + if authReq.GetResponseMode() == oidc.ResponseModeFormPost { + err := AuthResponseFormPost(w, authReq.GetRedirectURI(), resp, authorizer.Encoder()) + if err != nil { + AuthRequestError(w, r, authReq, err, authorizer) + return + } + + return + } + callback, err := AuthResponseURL(authReq.GetRedirectURI(), authReq.GetResponseType(), authReq.GetResponseMode(), resp, authorizer.Encoder()) if err != nil { AuthRequestError(w, r, authReq, err, authorizer) @@ -535,6 +560,43 @@ func AuthResponseURL(redirectURI string, responseType oidc.ResponseType, respons return mergeQueryParams(uri, params), nil } +//go:embed form_post.html.tmpl +var formPostHtmlTemplate string + +var formPostTmpl = template.Must(template.New("form_post").Parse(formPostHtmlTemplate)) + +// AuthResponseFormPost responds a html page that automatically submits the form which contains the auth response parameters +func AuthResponseFormPost(res http.ResponseWriter, redirectURI string, response any, encoder httphelper.Encoder) error { + values := make(map[string][]string) + err := encoder.Encode(response, values) + if err != nil { + return oidc.ErrServerError().WithParent(err) + } + + params := &struct { + RedirectURI string + Params any + }{ + RedirectURI: redirectURI, + Params: values, + } + + var buf bytes.Buffer + err = formPostTmpl.Execute(&buf, params) + if err != nil { + return oidc.ErrServerError().WithParent(err) + } + + res.Header().Set("Cache-Control", "no-store") + res.WriteHeader(http.StatusOK) + _, err = buf.WriteTo(res) + if err != nil { + return oidc.ErrServerError().WithParent(err) + } + + return nil +} + func setFragment(uri *url.URL, params url.Values) string { uri.Fragment = params.Encode() return uri.String() diff --git a/pkg/op/auth_request_test.go b/pkg/op/auth_request_test.go index 2e7c75c..76cb00d 100644 --- a/pkg/op/auth_request_test.go +++ b/pkg/op/auth_request_test.go @@ -1027,9 +1027,10 @@ func TestAuthResponseCode(t *testing.T) { authorizer func(*testing.T) op.Authorizer } type res struct { - wantCode int - wantLocationHeader string - wantBody string + wantCode int + wantLocationHeader string + wantCacheControlHeader string + wantBody string } tests := []struct { name string @@ -1111,6 +1112,33 @@ func TestAuthResponseCode(t *testing.T) { wantBody: "", }, }, + { + name: "success form_post", + args: args{ + authReq: &storage.AuthRequest{ + ID: "id1", + CallbackURI: "https://example.com/callback", + TransferState: "state1", + ResponseMode: "form_post", + }, + authorizer: func(t *testing.T) op.Authorizer { + ctrl := gomock.NewController(t) + storage := mock.NewMockStorage(ctrl) + storage.EXPECT().SaveAuthCode(context.Background(), "id1", "id1") + + authorizer := mock.NewMockAuthorizer(ctrl) + authorizer.EXPECT().Storage().Return(storage) + authorizer.EXPECT().Crypto().Return(&mockCrypto{}) + authorizer.EXPECT().Encoder().Return(schema.NewEncoder()) + return authorizer + }, + }, + res: res{ + wantCode: http.StatusOK, + wantCacheControlHeader: "no-store", + wantBody: "\n\n\n\n
\n\n\n\n\n\n\n
\n\n", + }, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -1121,6 +1149,7 @@ func TestAuthResponseCode(t *testing.T) { defer resp.Body.Close() assert.Equal(t, tt.res.wantCode, resp.StatusCode) assert.Equal(t, tt.res.wantLocationHeader, resp.Header.Get("Location")) + assert.Equal(t, tt.res.wantCacheControlHeader, resp.Header.Get("Cache-Control")) body, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, tt.res.wantBody, string(body)) diff --git a/pkg/op/form_post.html.tmpl b/pkg/op/form_post.html.tmpl new file mode 100644 index 0000000..7bc9ab3 --- /dev/null +++ b/pkg/op/form_post.html.tmpl @@ -0,0 +1,14 @@ + + + + +
+{{with .Params.state}}{{end}} +{{with .Params.code}}{{end}} +{{with .Params.id_token}}{{end}} +{{with .Params.access_token}}{{end}} +{{with .Params.token_type}}{{end}} +{{with .Params.expires_in}}{{end}} +
+ + \ No newline at end of file