59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
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) {
|
|
return []byte(config.Cfg.Security.Jwt.Secret), nil
|
|
})
|
|
|
|
if token != nil && token.Valid {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
func NewToken(expire time.Duration, auds ...string) (string, error) {
|
|
if len(auds) == 0 {
|
|
auds = []string{"non-audience"}
|
|
}
|
|
// Create the claims
|
|
claims := JwtClaims{
|
|
"bar",
|
|
jwt.RegisteredClaims{
|
|
// A usual scenario is to set the expiration time relative to the current time
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expire)),
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
NotBefore: jwt.NewNumericDate(time.Now()),
|
|
Issuer: "drivelinked",
|
|
Subject: "login",
|
|
Audience: auds,
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
ss, err := token.SignedString([]byte(config.Cfg.Security.Jwt.Secret))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return ss, nil
|
|
}
|
|
|
|
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)
|
|
}
|