jwt.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package middleware
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/Nerzal/gocloak/v13"
  6. "github.com/gofrs/uuid"
  7. "github.com/golang-jwt/jwt/v4"
  8. echojwt "github.com/labstack/echo-jwt/v4"
  9. "github.com/labstack/echo/v4"
  10. )
  11. func Jwt(issuer string) echo.MiddlewareFunc {
  12. var (
  13. sKeyJwtToken = fmt.Sprintf("%s", keyJwtToken)
  14. cli = gocloak.NewClient(issuer)
  15. cfg = echojwt.Config{
  16. ContinueOnIgnoredError: true,
  17. ErrorHandler: func(c echo.Context, err error) error {
  18. return nil
  19. },
  20. ContextKey: sKeyJwtToken,
  21. ParseTokenFunc: func(c echo.Context, auth string) (interface{}, error) {
  22. var (
  23. ctx = c.Request().Context()
  24. projectId uuid.UUID
  25. token *jwt.Token
  26. err error
  27. )
  28. if projectId, err = GetInstanceId(ctx); err != nil || projectId == uuid.Nil {
  29. return nil, fmt.Errorf("missing or malformed instance id")
  30. }
  31. if token, _, err = cli.DecodeAccessToken(ctx, auth, projectId.String()); err != nil {
  32. return nil, err
  33. }
  34. if !token.Valid {
  35. return nil, fmt.Errorf("invalid access token")
  36. }
  37. return token, err
  38. },
  39. SuccessHandler: func(ctx echo.Context) {
  40. value := context.WithValue(ctx.Request().Context(), keyJwtToken, ctx.Get(sKeyJwtToken))
  41. ctx.SetRequest(ctx.Request().WithContext(value))
  42. },
  43. }
  44. )
  45. return echojwt.WithConfig(cfg)
  46. }
  47. func GetToken(ctx context.Context) (*jwt.Token, error) {
  48. t, ok := ctx.Value(keyJwtToken).(*jwt.Token)
  49. if !ok {
  50. return nil, fmt.Errorf("missing or malformed token")
  51. }
  52. return t, nil
  53. }