12345678910111213141516171819202122232425262728293031323334353637383940 |
- package common
- import (
- "AIT/global"
- "AIT/models"
- "github.com/golang-jwt/jwt"
- "time"
- )
- var SigningKey = []byte(global.Config.Jwt.SigningKey)
- const TokenExpireDuration = time.Hour * 2
- type Claims struct {
- models.User
- Username string `json:"username"`
- jwt.StandardClaims
- }
- // GenerateToke 生成Token
- func GenerateToke(user models.User) (string, error) {
- expirationTime := time.Now().Add(TokenExpireDuration)
- user.Password = ""
- claims := Claims{
- user, user.UserName, jwt.StandardClaims{
- ExpiresAt: expirationTime.Unix(),
- Issuer: user.UserName,
- },
- }
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
- return token.SignedString(SigningKey)
- }
- // VerifyToken 验证Token
- func VerifyToken(tokenString string) error {
- _, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
- return SigningKey, nil
- })
- return err
- }
|