jwt.go 875 Bytes
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
package pkg

import (
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"hilo/app/service/user/internal/conf"
	"time"
)

// Claims 载荷,增加用户别名
type Claims struct {
	UserId     int64
	ExternalId string
	jwt.StandardClaims
}

func GenerateJwtToken(userId int64, externalId string) (string, error) {
	jwtConfig := conf.Conf.Auth.Jwt
	duration, err := time.ParseDuration(jwtConfig.Expire)
	if err != nil {
		return "", fmt.Errorf("jwt parse time err: %s", err)
	}

	expireTime := time.Now().Add(duration)
	claims := Claims{
		UserId:     userId,
		ExternalId: externalId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), //过期时间
			Issuer:    jwtConfig.Issuer,  //签名的发行者
		},
	}
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString([]byte(jwtConfig.Secret))
	return token, err
}