diff --git a/context.go b/context.go index baa4b0f9c9..396f8ac6ad 100644 --- a/context.go +++ b/context.go @@ -1066,7 +1066,14 @@ func (c *Context) String(code int, format string, values ...any) { } // Redirect returns an HTTP redirect to the specific location. +// When the 'location' parameter is empty, it poses a potential security risk. +// Avoid bringing potential security risks into the production environment. func (c *Context) Redirect(code int, location string) { + if IsDebugging() && location == "" { + debugPrint(`[WARNING] When the 'location' parameter is empty, it poses a potential security risk. Please input a secure redirection URL to ensure safe operation.`) + location = "/" + } + c.Render(-1, render.Redirect{ Code: code, Location: location, diff --git a/context_test.go b/context_test.go index 66190b302e..7148a8ae77 100644 --- a/context_test.go +++ b/context_test.go @@ -1217,6 +1217,18 @@ func TestContextRenderRedirectWith201(t *testing.T) { assert.Equal(t, "/resource", w.Header().Get("Location")) } +func TestContextRenderRedirectWithEmptyPath(t *testing.T) { + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + + c.Request, _ = http.NewRequest("POST", "http://example.com", nil) + c.Redirect(http.StatusTemporaryRedirect, "") + c.Writer.WriteHeaderNow() + + assert.Equal(t, http.StatusTemporaryRedirect, w.Code) + assert.Equal(t, "/", w.Header().Get("Location")) +} + func TestContextRenderRedirectAll(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "http://example.com", nil) diff --git a/docs/doc.md b/docs/doc.md index b76011f2ab..414431df7e 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -1496,6 +1496,8 @@ Gin allow by default use only one html.Template. Check [a multitemplate render]( Issuing a HTTP redirect is easy. Both internal and external locations are supported. +Note: When the location is empty, there is a security risk. Please do not bring it to production + ```go r.GET("/test", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")