Passport/pkg/internal/services/jwt.go

69 lines
1.6 KiB
Go
Raw Normal View History

2024-04-20 11:04:33 +00:00
package services
2024-01-06 17:56:32 +00:00
import (
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/spf13/viper"
)
type PayloadClaims struct {
jwt.RegisteredClaims
2024-07-28 11:50:49 +00:00
AuthorizedParties string `json:"azp,omitempty"`
SessionID string `json:"sed"`
Type string `json:"typ"`
2024-01-06 17:56:32 +00:00
}
const (
JwtAccessType = "access"
JwtRefreshType = "refresh"
)
func EncodeJwt(id string, typ, sub, sed string, aud []string, exp time.Time) (string, error) {
2024-07-28 11:50:49 +00:00
var azp string
for _, item := range aud {
if item != InternalTokenAudience {
azp = item
break
}
}
2024-01-06 17:56:32 +00:00
tk := jwt.NewWithClaims(jwt.SigningMethodHS512, PayloadClaims{
2024-07-28 11:50:49 +00:00
RegisteredClaims: jwt.RegisteredClaims{
2024-01-06 17:56:32 +00:00
Subject: sub,
Audience: aud,
2024-01-30 13:24:54 +00:00
Issuer: fmt.Sprintf("https://%s", viper.GetString("domain")),
2024-01-06 17:56:32 +00:00
ExpiresAt: jwt.NewNumericDate(exp),
NotBefore: jwt.NewNumericDate(time.Now()),
IssuedAt: jwt.NewNumericDate(time.Now()),
ID: id,
},
2024-07-28 11:50:49 +00:00
AuthorizedParties: azp,
SessionID: sed,
Type: typ,
2024-01-06 17:56:32 +00:00
})
return tk.SignedString([]byte(viper.GetString("secret")))
}
func DecodeJwt(str string) (PayloadClaims, error) {
var claims PayloadClaims
tk, err := jwt.ParseWithClaims(str, &claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(viper.GetString("secret")), nil
})
if err != nil {
return claims, err
}
if data, ok := tk.Claims.(*PayloadClaims); ok {
return *data, nil
} else {
return claims, fmt.Errorf("unexpected token payload: not payload claims type")
}
}