Skip to content

Commit

Permalink
feat: Add a new ErrorHandlerWithContext (#1328)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
tomscholz authored and vishr committed Jun 13, 2019
1 parent 6b9408d commit 3136157
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions middleware/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ type (
// ErrorHandler defines a function which is executed for an invalid token.
// It may be used to define a custom JWT error.
ErrorHandler JWTErrorHandler

// ErrorHandlerWithContext is almost identical to ErrorHandler, but it's passed the current context.
ErrorHandlerWithContext JWTErrorHandlerWithContext

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

// JWTErrorHandlerWithContext is almost identical to JWTErrorHandler, but it's passed the current context.
JWTErrorHandlerWithContext func(error, echo.Context) error

jwtExtractor func(echo.Context) (string, error)
)

Expand Down Expand Up @@ -177,6 +183,10 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
if config.ErrorHandler != nil {
return config.ErrorHandler(err)
}

if config.ErrorHandlerWithContext != nil {
return config.ErrorHandlerWithContext(err, c)
}
return err
}
token := new(jwt.Token)
Expand All @@ -199,6 +209,9 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
if config.ErrorHandler != nil {
return config.ErrorHandler(err)
}
if config.ErrorHandlerWithContext != nil {
return config.ErrorHandlerWithContext(err, c)
}
return &echo.HTTPError{
Code: http.StatusUnauthorized,
Message: "invalid or expired jwt",
Expand Down

0 comments on commit 3136157

Please sign in to comment.