当我编译新代码时,Go的JWT令牌到期

时间:2018-03-31 04:07:53

标签: go jwt

我正在开发基于SAAS的产品,该产品在前端的Angular5中构建。它使用Go的rest API连接到DB和所有后端功能。我正在使用JWT令牌来验证此系统上的用户。

在后端,我使用Gin框架进行API路由和响应处理。

我面临的问题是,当我在服务器上编译最新代码时。令牌过期,它要求我再次登录以生成新令牌。

我用来生成JWT的代码如下:

package main

import (
    "github.com/dgrijalva/jwt-go"
    "github.com/gin-gonic/contrib/sessions"
)

func CreateToken(user models.User, c *gin.Context) (string, error){
    var ip, userAgent string
    keyError := config.InitKeys()
    if keyError != nil{
        return "", keyError
    }
    if values, _ := c.Request.Header["Ip"]; len(values) > 0 {
        ip = values[0]
    }

    if values, _ := c.Request.Header["User-Agent"]; len(values) > 0{
        userAgent = values[0]
    }


    token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.MapClaims{
        "email": user.EmailId,
        "exp":   time.Now().Add(time.Hour * 8).Unix(),
        "role": user.Role,
        "name":  user.FirstName+" "+user.LastName,
        "ip": ip,
        "user_agent": userAgent,
        "id": user.Id,
    })

    config.CurrentUserId    = user.Id
    models.CurrentUser      = user

    // Sign and get the complete encoded token as a string
    tokenString, err        := token.SignedString([]byte(config.SignKey))

    return tokenString, err
}

将代码与前端标题中发送的令牌进行比较的代码为:

if values, _ := c.Request.Header["Authorization"]; len(values) > 0 {
        bearer := strings.Split(c.Request.Header["Authorization"][0], "Bearer")
        bearerToken := strings.TrimSpace(bearer[1])
        _, err := merchantDb.GetSession(bson.M{"token": bearerToken})
        if err != nil{
            errMsg := "Failed: Unauthorized Access."
            response := controllers.ResponseController{
                config.FailureCode,
                config.FailureFlag,
                errMsg,
                nil,
            }
            controllers.GetResponse(c, response)
            c.Abort()
        }else{

            var ip, userAgent string
            var ipCheck, userAgentCheck bool

            if values, _ := c.Request.Header["Ip"]; len(values) > 0 {
                ip = values[0]
            }

            if values, _ := c.Request.Header["User-Agent"]; len(values) > 0{
                userAgent = values[0]
            }

            token, err := jwt.Parse(bearerToken, func(token *jwt.Token) (interface{}, error) {
                return config.SignKey, nil
            })
            if len (token.Claims.(jwt.MapClaims)) > 0{
                for key, claim := range token.Claims.(jwt.MapClaims) {
                    if key == "ip" {
                        if claim == ip{
                            ipCheck = true
                        }
                    }

                    if key == "user_agent"{
                        if claim == userAgent{
                            userAgentCheck = true
                        }
                    }   

                    if key == "role"{
                        role = claim.(string)
                    }

                    if key == "id"{
                        userId = claim.(float64)
                    }
                    if key == "name"{
                        userName = claim.(string)
                    }
                }
            }
            merchantDatabase["userid"] = userId
            merchantDatabase["role"] = role
            merchantDatabase["username"] = userName
            c.Keys = merchantDatabase
            if err == nil && token.Valid && ipCheck == true && userAgentCheck == true {
                c.Next()
            } else {
                errMsg := "Failed: Invalid Token."
                response := controllers.ResponseController{
                    config.FailureCode,
                    config.FailureFlag,
                    errMsg,
                    nil,
                }
                controllers.GetResponse(c, response)
                c.Abort()
            }
        }
    }else{
        errMsg := "Failed: Unauthorized Access."
        response := controllers.ResponseController{
            config.FailureCode,
            config.FailureFlag,
            errMsg,
            nil,
        }
        controllers.GetResponse(c, response)
        c.Abort()
    }

这个问题耗费了大量时间。如果有人知道问题,请回复此帖。

谢谢!

1 个答案:

答案 0 :(得分:0)

我怀疑你的会话有问题

_, err := merchantDb.GetSession(bson.M{"token": bearerToken})

或其他内容,因为您没有共享完整代码。也许,你的SigningKeys在构建之间不一致。 我为你写了一个小测试来证明jwt令牌不会在go之间过期

package main

import (
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "time"
)

func CreateToken() (string, error) {

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.MapClaims{
        "email":      "test@email.com",
        "exp":        time.Now().Add(time.Hour * 240).Unix(),
        //"exp":        time.Now().Add(-time.Hour * 8).Unix(),
        "role":       "test role",
        "name":       "test name",
        "ip":         "1.1.1.1",
        "user_agent": "test agent",
        "id":         "123",
    })

    // Sign and get the complete encoded token as a string
    tokenString, err := token.SignedString([]byte("AllYourBase"))

    return tokenString, err
}
func main() {

    //tokenString,_ := CreateToken()
    tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAZW1haWwuY29tIiwiZXhwIjoxNTIzNjAwOTM1LCJpZCI6IjEyMyIsImlwIjoiMS4xLjEuMSIsIm5hbWUiOiJ0ZXN0IG5hbWUiLCJyb2xlIjoidGVzdCByb2xlIiwidXNlcl9hZ2VudCI6InRlc3QgYWdlbnQifQ.UCD3P5-ua3qgTvy_-7hmHEVPPZwFCbhmRJNqndBwtes"
    token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        return []byte("AllYourBase"), nil
    })
    fmt.Println(token)
    fmt.Println(token.Valid)
}

正如您可以查看的那样,无论您在何处运行此代码,tokenString都将在接下来的10天内生效