JWT Middleware

JWT provides a JSON Web Token (JWT) authentication middleware.

  • For valid token, it sets the user in context and calls next handler.
  • For invalid token, it sends “401 - Unauthorized” response.
  • For missing or invalid Authorization header, it sends “400 - Bad Request”.

Usage

e.Use(middleware.JWT([]byte("secret"))

Custom Configuration

Usage

  1. e.Use(middleware.JWTWithConfig(middleware.JWTConfig{
  2. SigningKey: []byte("secret"),
  3. TokenLookup: "query:token",
  4. }))

Configuration

  1. JWTConfig struct {
  2. // Skipper defines a function to skip middleware.
  3. Skipper Skipper
  4. // Signing key to validate token.
  5. // Required.
  6. SigningKey interface{}
  7. // Signing method, used to check token signing method.
  8. // Optional. Default value HS256.
  9. SigningMethod string
  10. // Context key to store user information from the token into context.
  11. // Optional. Default value "user".
  12. ContextKey string
  13. // Claims are extendable claims data defining token content.
  14. // Optional. Default value jwt.MapClaims
  15. Claims jwt.Claims
  16. // TokenLookup is a string in the form of "<source>:<name>" that is used
  17. // to extract token from the request.
  18. // Optional. Default value "header:Authorization".
  19. // Possible values:
  20. // - "header:<name>"
  21. // - "query:<name>"
  22. // - "cookie:<name>"
  23. TokenLookup string
  24. // AuthScheme to be used in the Authorization header.
  25. // Optional. Default value "Bearer".
  26. AuthScheme string
  27. }

Default Configuration

  1. DefaultJWTConfig = JWTConfig{
  2. Skipper: DefaultSkipper,
  3. SigningMethod: AlgorithmHS256,
  4. ContextKey: "user",
  5. TokenLookup: "header:" + echo.HeaderAuthorization,
  6. AuthScheme: "Bearer",
  7. Claims: jwt.MapClaims{},
  8. }

Example