Skip to content

Commit 3136157

Browse files
tomscholzvishr
authored andcommitted
feat: Add a new ErrorHandlerWithContext (#1328)
* feat: Add a new ErrorHandlerWithContext This commit adds a new error handler, which is passed the current context, so that you can add custom redirects or even other kinds of responses. For example: ```go e.Use(middleware.JWTWithConfig(middleware.JWTConfig{ SigningKey: []byte("secret"), TokenLookup: "query:token", ErrorHandlerWithContext: func(err error, c echo.Context) error { // do stuff with context and err switch err.(type) { case jwt.ValidationError: return c.Redirect(http.StatusSeeOther, "/login") } return err }, })) ``` * chore: address golint issues
1 parent 6b9408d commit 3136157

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

middleware/jwt.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ type (
2525
// ErrorHandler defines a function which is executed for an invalid token.
2626
// It may be used to define a custom JWT error.
2727
ErrorHandler JWTErrorHandler
28+
29+
// ErrorHandlerWithContext is almost identical to ErrorHandler, but it's passed the current context.
30+
ErrorHandlerWithContext JWTErrorHandlerWithContext
2831

2932
// Signing key to validate token. Used as fallback if SigningKeys has length 0.
3033
// Required. This or SigningKeys.
@@ -69,6 +72,9 @@ type (
6972
// JWTErrorHandler defines a function which is executed for an invalid token.
7073
JWTErrorHandler func(error) error
7174

75+
// JWTErrorHandlerWithContext is almost identical to JWTErrorHandler, but it's passed the current context.
76+
JWTErrorHandlerWithContext func(error, echo.Context) error
77+
7278
jwtExtractor func(echo.Context) (string, error)
7379
)
7480

@@ -177,6 +183,10 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
177183
if config.ErrorHandler != nil {
178184
return config.ErrorHandler(err)
179185
}
186+
187+
if config.ErrorHandlerWithContext != nil {
188+
return config.ErrorHandlerWithContext(err, c)
189+
}
180190
return err
181191
}
182192
token := new(jwt.Token)
@@ -199,6 +209,9 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
199209
if config.ErrorHandler != nil {
200210
return config.ErrorHandler(err)
201211
}
212+
if config.ErrorHandlerWithContext != nil {
213+
return config.ErrorHandlerWithContext(err, c)
214+
}
202215
return &echo.HTTPError{
203216
Code: http.StatusUnauthorized,
204217
Message: "invalid or expired jwt",

0 commit comments

Comments
 (0)