jwt_instance.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package jwt
  2. import (
  3. "errors"
  4. "github.com/golang-jwt/jwt/v5"
  5. "strings"
  6. )
  7. // Option describes the jwt extra data
  8. type Option struct {
  9. Key string
  10. Val any
  11. }
  12. // WithOption returns the option from k/v
  13. func WithOption(key string, val any) Option {
  14. return Option{
  15. Key: key,
  16. Val: val,
  17. }
  18. }
  19. // NewJwtToken returns the jwt token from the given data.
  20. func NewJwtToken(secretKey string, iat, seconds int64, opt ...Option) (string, error) {
  21. claims := make(jwt.MapClaims)
  22. claims["exp"] = iat + seconds
  23. claims["iat"] = iat
  24. for _, v := range opt {
  25. claims[v.Key] = v.Val
  26. }
  27. token := jwt.New(jwt.SigningMethodHS256)
  28. token.Claims = claims
  29. return token.SignedString([]byte(secretKey))
  30. }
  31. // ParseJwtToken parse the real content from jwt string.
  32. func ParseJwtToken(secretKey, tokenStr string) (map[string]interface{}, error) {
  33. if secretKey == "" || tokenStr == "" {
  34. return nil, errors.New("invalid parameters")
  35. }
  36. claimsMap := make(jwt.MapClaims)
  37. token, err := jwt.ParseWithClaims(tokenStr, &claimsMap, func(token *jwt.Token) (interface{}, error) {
  38. return []byte(secretKey), nil
  39. })
  40. if err != nil {
  41. return nil, err
  42. }
  43. if claims, ok := token.Claims.(*jwt.MapClaims); ok {
  44. return *claims, nil
  45. }
  46. return nil, errors.New("unknown error")
  47. }
  48. // StripBearerPrefixFromToken remove the bearer prefix in token string.
  49. func StripBearerPrefixFromToken(token string) string {
  50. if len(token) > 6 && strings.ToUpper(token[0:7]) == "BEARER " {
  51. return token[7:]
  52. }
  53. return token
  54. }