jwt.go 936 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package middleware
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/golang-jwt/jwt/v4"
  6. echojwt "github.com/labstack/echo-jwt/v4"
  7. "github.com/labstack/echo/v4"
  8. )
  9. func Jwt(parser func(c echo.Context, auth string) (interface{}, error)) echo.MiddlewareFunc {
  10. var (
  11. sKeyJwtToken = fmt.Sprintf("%s", keyJwtToken)
  12. cfg = echojwt.Config{
  13. ContinueOnIgnoredError: true,
  14. ErrorHandler: func(c echo.Context, err error) error {
  15. return nil
  16. },
  17. ContextKey: sKeyJwtToken,
  18. ParseTokenFunc: parser,
  19. SuccessHandler: func(ctx echo.Context) {
  20. value := context.WithValue(ctx.Request().Context(), keyJwtToken, ctx.Get(sKeyJwtToken))
  21. ctx.SetRequest(ctx.Request().WithContext(value))
  22. },
  23. }
  24. )
  25. return echojwt.WithConfig(cfg)
  26. }
  27. func GetToken(ctx context.Context) (*jwt.Token, error) {
  28. t, ok := ctx.Value(keyJwtToken).(*jwt.Token)
  29. if !ok {
  30. return nil, fmt.Errorf("missing or malformed token")
  31. }
  32. return t, nil
  33. }