JWT 中间件

JWT 提供了一个 JSON Web Token (JWT) 认证中间件。

  • 对于有效的 token,它将用户置于上下文中并调用下一个处理程序。
  • 对于无效的 token,它会发送 “401 - Unauthorized” 响应。
  • 对于丢失或无效的 Authorization 标头,它会发送 “400 - Bad Request” 。

用法

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

自定义配置

用法

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

配置

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

默认配置

  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. }

示例