123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- package middleware
- import (
- "context"
- "fmt"
- "github.com/Nerzal/gocloak/v13"
- "github.com/gofrs/uuid"
- "github.com/golang-jwt/jwt/v4"
- echojwt "github.com/labstack/echo-jwt/v4"
- "github.com/labstack/echo/v4"
- )
- func Jwt(issuer string) echo.MiddlewareFunc {
- var (
- sKeyJwtToken = fmt.Sprintf("%s", keyJwtToken)
- cli = gocloak.NewClient(issuer)
- cfg = echojwt.Config{
- ContinueOnIgnoredError: true,
- ErrorHandler: func(c echo.Context, err error) error {
- return nil
- },
- ContextKey: sKeyJwtToken,
- ParseTokenFunc: func(c echo.Context, auth string) (interface{}, error) {
- var (
- ctx = c.Request().Context()
- projectId uuid.UUID
- token *jwt.Token
- err error
- )
- if projectId, err = GetInstanceId(ctx); err != nil || projectId == uuid.Nil {
- return nil, fmt.Errorf("missing or malformed instance id")
- }
- if token, _, err = cli.DecodeAccessToken(ctx, auth, projectId.String()); err != nil {
- return nil, err
- }
- if !token.Valid {
- return nil, fmt.Errorf("invalid access token")
- }
- return token, err
- },
- SuccessHandler: func(ctx echo.Context) {
- value := context.WithValue(ctx.Request().Context(), keyJwtToken, ctx.Get(sKeyJwtToken))
- ctx.SetRequest(ctx.Request().WithContext(value))
- },
- }
- )
- return echojwt.WithConfig(cfg)
- }
- func GetToken(ctx context.Context) (*jwt.Token, error) {
- t, ok := ctx.Value(keyJwtToken).(*jwt.Token)
- if !ok {
- return nil, fmt.Errorf("missing or malformed token")
- }
- return t, nil
- }
|