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 ValidateLogin(token string) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewToken(auds ...string) (string, error) {
|
2022-04-03 13:29:47 +08:00
|
|
|
if len(auds) == 0 {
|
|
|
|
auds = []string{"nonAudience"}
|
|
|
|
}
|
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
|
|
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(config.Cfg.Security.Jwt.Expire) * time.Second)),
|
|
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
|
|
NotBefore: jwt.NewNumericDate(time.Now()),
|
|
|
|
Issuer: "drivelinked",
|
|
|
|
Subject: "login",
|
2022-04-03 13:29:47 +08:00
|
|
|
Audience: auds,
|
2022-04-03 12:30:50 +08:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2022-04-03 13:29:47 +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
|
|
|
|
}
|