DriveLinked/pkg/common/token.go

59 lines
1.3 KiB
Go
Raw Normal View History

2022-04-03 12:30:50 +08:00
package common
import (
"drive-linked/config"
"github.com/golang-jwt/jwt/v4"
"time"
)
type JwtClaims struct {
Foo string `json:"foo"`
jwt.RegisteredClaims
}
//TODO:token解密验证
func VerifyToken(authorization string) error {
token, err := jwt.Parse(authorization, func(token *jwt.Token) (interface{}, error) {
2022-04-05 18:16:20 +08:00
return []byte(config.Cfg.Security.Jwt.Secret), nil
})
if token != nil && token.Valid {
return nil
}
return err
2022-04-03 12:30:50 +08:00
}
2022-04-09 11:48:44 +08:00
func NewToken(expire time.Duration, auds ...string) (string, error) {
if len(auds) == 0 {
2022-04-05 18:16:20 +08:00
auds = []string{"non-audience"}
}
2022-04-03 12:30:50 +08:00
// Create the claims
claims := JwtClaims{
"bar",
jwt.RegisteredClaims{
// A usual scenario is to set the expiration time relative to the current time
2022-04-09 11:48:44 +08:00
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expire)),
2022-04-03 12:30:50 +08:00
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: "drivelinked",
Subject: "login",
Audience: auds,
2022-04-03 12:30:50 +08:00
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString([]byte(config.Cfg.Security.Jwt.Secret))
2022-04-03 12:30:50 +08:00
if err != nil {
return "", err
}
return ss, nil
}
2022-04-09 11:48:44 +08:00
func NewShortToken(auds ...string) (string, error) {
return NewToken(time.Duration(config.Cfg.Security.Jwt.Expire) * time.Second)
}
func NewRefreshToken(auds ...string) (string, error) {
return NewToken(24 * time.Hour)
}