我正在研究基于SAAS的产品。我正在使用JWT方法对系统中登录的用户进行身份验证。该产品是在Go后端使用gin框架进行路由开发的。
问题
当用户登录时,将生成其JWT令牌并运行良好。现在,用户没有注销,而是关闭了浏览器选项卡或窗口。在他回来之前,请使用install命令重新安装go应用。现在,用户返回并访问他的帐户,令牌已过期,并且他看不到任何详细信息。
以下是在登录时生成令牌的代码:
func CreateToken(user models.User, c *gin.Context) (string, error){
var ip, userAgent string
keyError := 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 * 8760).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
}
func InitKeys()(err error){
SignKey, err = ioutil.ReadFile(GetBasePath()+PrivateKeyPath)
if err != nil {
return err
}
VerifyKey, err = ioutil.ReadFile(GetBasePath()+PublicKeyPath)
if err != nil {
return err
}
return nil
}
现在使用以下功能对令牌进行解码和匹配:
func ParseJWTToken(c *gin.Context){
merchantDb := models.MerchantDatabase{ c.Keys["merchant_db"].(string) }
merchantDatabase := make(map[string]interface{})
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,
err,
}
controllers.GetResponse(c, response)
c.Abort()
}else{
var userAgent string
var userAgentCheck bool
if values, _ := c.Request.Header["User-Agent"]; len(values) > 0 {
userAgent = values[0]
}
_ = config.InitKeys()
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 == "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 && 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,
"Missing Authorization Header",
}
controllers.GetResponse(c, response)
c.Abort()
}
}
我无法检测到我所缺少的东西。请调查代码,并指导我在这种情况下应该怎么做。