mirror of
https://github.com/yv1ing/gin-admin.git
synced 2025-10-24 10:12:05 +08:00
添加jwt鉴权中间件
This commit is contained in:
54
pkg/auth/jwt.go
Normal file
54
pkg/auth/jwt.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"time"
|
||||
)
|
||||
|
||||
// @Author: yv1ing
|
||||
// @Author: me@yvling.cn
|
||||
// @Date: 2025/8/28 15:54
|
||||
// @Desc: jwt鉴权方法
|
||||
|
||||
type AccessClaims struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func CreateAccessToken(ID uint, username string, secretKey string) (string, error) {
|
||||
jwtSecret := []byte(secretKey)
|
||||
|
||||
claims := AccessClaims{
|
||||
ID: ID,
|
||||
Username: username,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: "gin-admin",
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(12 * time.Hour)),
|
||||
ID: fmt.Sprintf("%d-%d", ID, time.Now().UnixNano()),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(jwtSecret)
|
||||
}
|
||||
|
||||
func ParseAccessToken(tokenStr, secretKey string) (*AccessClaims, error) {
|
||||
jwtSecret := []byte(secretKey)
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &AccessClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return jwtSecret, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*AccessClaims); ok && token.Valid {
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("token非法")
|
||||
}
|
||||
Reference in New Issue
Block a user