🎨每次请求都重新生成token

This commit is contained in:
coward 2024-07-12 16:32:31 +08:00
parent 11d649cfc3
commit 9af89ee41f
2 changed files with 28 additions and 5 deletions

View File

@ -36,11 +36,19 @@ func JWT() JwtComponent {
// @return token // @return token
// @return expireTime // @return expireTime
// @return err // @return err
func (JwtComponent) GenerateToken(userId, secret string) (token string, expireTime *jwt.NumericDate, err error) { func (JwtComponent) GenerateToken(userId, secret string, times ...time.Time) (token string, expireTime *jwt.NumericDate, err error) {
var notBefore, issuedAt *jwt.NumericDate
if len(times) != 0 {
expireTime = jwt.NewNumericDate(times[0])
notBefore = jwt.NewNumericDate(times[1])
issuedAt = jwt.NewNumericDate(times[1])
} else {
timeNow := time.Now().Local() timeNow := time.Now().Local()
expireTime = jwt.NewNumericDate(timeNow.Add(7 * time.Hour)) expireTime = jwt.NewNumericDate(timeNow.Add(7 * time.Hour))
notBefore := jwt.NewNumericDate(timeNow) notBefore = jwt.NewNumericDate(timeNow)
issuedAt := jwt.NewNumericDate(timeNow) issuedAt = jwt.NewNumericDate(timeNow)
}
claims := JwtComponent{ claims := JwtComponent{
ID: userId, ID: userId,
RegisteredClaims: jwt.RegisteredClaims{ RegisteredClaims: jwt.RegisteredClaims{

View File

@ -1,8 +1,11 @@
package middleware package middleware
import ( import (
"fmt"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/google/uuid"
"strings" "strings"
"time"
"wireguard-ui/component" "wireguard-ui/component"
"wireguard-ui/global/constant" "wireguard-ui/global/constant"
"wireguard-ui/http/response" "wireguard-ui/http/response"
@ -59,6 +62,18 @@ func Authorization() gin.HandlerFunc {
// 将用户信息放入上下文 // 将用户信息放入上下文
c.Set("user", &user) c.Set("user", &user)
// 生成一个新token
secret := component.JWT().GenerateSecret(user.Password, uuid.NewString(), time.Now().Local().String())
tokenStr, _, err := component.JWT().GenerateToken(user.Id, secret, userClaims.ExpiresAt.Time, userClaims.IssuedAt.Time)
if err != nil {
response.R(c).AuthorizationFailed("校验失败")
c.Abort()
return
}
c.Writer.Header().Set("Authorization", fmt.Sprintf("Bearer %s", tokenStr))
c.Writer.Header().Set("X-TOKEN", secret)
c.Next() c.Next()
} }
} }