Skip to content

Commit 11208ce

Browse files
committed
SuccessHandler can return error and break handler chain execution
1 parent 9052334 commit 11208ce

2 files changed

Lines changed: 35 additions & 3 deletions

File tree

jwt.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ type Config struct {
2222
BeforeFunc middleware.BeforeFunc
2323

2424
// SuccessHandler defines a function which is executed for a valid token.
25-
SuccessHandler func(c *echo.Context)
25+
// In case SuccessHandler error the middleware stops handler chain execution and
26+
// returns error.
27+
SuccessHandler func(c *echo.Context) error
2628

2729
// ErrorHandler defines a function which is executed when all lookups have been done and none of them passed Validator
2830
// function. ErrorHandler is executed with last missing (ErrExtractionValueMissing) or an invalid key.
@@ -244,7 +246,9 @@ func (config Config) ToMiddleware() (echo.MiddlewareFunc, error) {
244246
// Store user information from token into context.
245247
c.Set(config.ContextKey, token)
246248
if config.SuccessHandler != nil {
247-
config.SuccessHandler(c)
249+
if sErr := config.SuccessHandler(c); sErr != nil {
250+
return sErr
251+
}
248252
}
249253
return next(c)
250254
}

jwt_test.go

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -642,8 +642,9 @@ func TestMustJWTWithConfig_SuccessHandler(t *testing.T) {
642642
ParseTokenFunc: func(c *echo.Context, auth string) (interface{}, error) {
643643
return auth, nil
644644
},
645-
SuccessHandler: func(c *echo.Context) {
645+
SuccessHandler: func(c *echo.Context) error {
646646
c.Set("success", "yes")
647+
return nil
647648
},
648649
}.ToMiddleware()
649650
assert.NoError(t, err)
@@ -658,6 +659,33 @@ func TestMustJWTWithConfig_SuccessHandler(t *testing.T) {
658659
assert.Equal(t, http.StatusTeapot, res.Code)
659660
}
660661

662+
func TestMustJWTWithConfig_SuccessHandlerError(t *testing.T) {
663+
e := echo.New()
664+
665+
e.GET("/", func(c *echo.Context) error {
666+
return c.String(http.StatusTeapot, "should not end up here")
667+
})
668+
669+
mw, err := Config{
670+
ParseTokenFunc: func(c *echo.Context, auth string) (interface{}, error) {
671+
return auth, nil
672+
},
673+
SuccessHandler: func(c *echo.Context) error {
674+
return echo.ErrForbidden.Wrap(errors.New("nope"))
675+
},
676+
}.ToMiddleware()
677+
assert.NoError(t, err)
678+
e.Use(mw)
679+
680+
req := httptest.NewRequest(http.MethodGet, "/", nil)
681+
req.Header.Add(echo.HeaderAuthorization, "Bearer valid_token_base64")
682+
res := httptest.NewRecorder()
683+
e.ServeHTTP(res, req)
684+
685+
assert.Equal(t, "{\"message\":\"Forbidden\"}\n", res.Body.String())
686+
assert.Equal(t, http.StatusForbidden, res.Code)
687+
}
688+
661689
func TestJWTWithConfig_ContinueOnIgnoredError(t *testing.T) {
662690
var testCases = []struct {
663691
name string

0 commit comments

Comments
 (0)