JWT token expired when Go app is installed











up vote
0
down vote

favorite
1












I am working on a SAAS based product. I am using JWT method to authenticate the logged in users in the system. The product is developed on Go on the backend with gin framework for routing.



Problem



When a user log in then its JWT token is generated and works well. Now the user did not logged out but closed the browser tab or window. Before he is back, the go app is re-installed with install command. Now the user come back and access his account, the token is expired and he could not see any of his details.



Following is the code to generate token while login:



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
}


Now to decode and match the token following function is used:



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()
}


}



I am not able to detect what I am missing. Please look into the code and guide me what should I do in this case.










share|improve this question






















  • What is your question? If a token has expired - it only means that it has expired, the expiration time is in the past.
    – zerkms
    Nov 13 at 7:37










  • @zerkms I have set the expiration time to 1 year. The point is it expires when I re-install my go app, which is wrong because neither expiration time is in the past nor the user logged out.
    – Amandeep kaur
    Nov 13 at 8:25










  • "The point is it expires" --- if you set expiration time of a JWT token to one year then it would expire in one year. Otherwise please define what you mean "it expires".
    – zerkms
    Nov 13 at 9:26












  • Actually it is not expired but it is not validated after installing the app.
    – Amandeep kaur
    Nov 13 at 10:18










  • What does "not validated" mean? Which error do you get, which line of code is or is not executed?
    – TommyF
    Nov 13 at 10:23















up vote
0
down vote

favorite
1












I am working on a SAAS based product. I am using JWT method to authenticate the logged in users in the system. The product is developed on Go on the backend with gin framework for routing.



Problem



When a user log in then its JWT token is generated and works well. Now the user did not logged out but closed the browser tab or window. Before he is back, the go app is re-installed with install command. Now the user come back and access his account, the token is expired and he could not see any of his details.



Following is the code to generate token while login:



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
}


Now to decode and match the token following function is used:



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()
}


}



I am not able to detect what I am missing. Please look into the code and guide me what should I do in this case.










share|improve this question






















  • What is your question? If a token has expired - it only means that it has expired, the expiration time is in the past.
    – zerkms
    Nov 13 at 7:37










  • @zerkms I have set the expiration time to 1 year. The point is it expires when I re-install my go app, which is wrong because neither expiration time is in the past nor the user logged out.
    – Amandeep kaur
    Nov 13 at 8:25










  • "The point is it expires" --- if you set expiration time of a JWT token to one year then it would expire in one year. Otherwise please define what you mean "it expires".
    – zerkms
    Nov 13 at 9:26












  • Actually it is not expired but it is not validated after installing the app.
    – Amandeep kaur
    Nov 13 at 10:18










  • What does "not validated" mean? Which error do you get, which line of code is or is not executed?
    – TommyF
    Nov 13 at 10:23













up vote
0
down vote

favorite
1









up vote
0
down vote

favorite
1






1





I am working on a SAAS based product. I am using JWT method to authenticate the logged in users in the system. The product is developed on Go on the backend with gin framework for routing.



Problem



When a user log in then its JWT token is generated and works well. Now the user did not logged out but closed the browser tab or window. Before he is back, the go app is re-installed with install command. Now the user come back and access his account, the token is expired and he could not see any of his details.



Following is the code to generate token while login:



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
}


Now to decode and match the token following function is used:



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()
}


}



I am not able to detect what I am missing. Please look into the code and guide me what should I do in this case.










share|improve this question













I am working on a SAAS based product. I am using JWT method to authenticate the logged in users in the system. The product is developed on Go on the backend with gin framework for routing.



Problem



When a user log in then its JWT token is generated and works well. Now the user did not logged out but closed the browser tab or window. Before he is back, the go app is re-installed with install command. Now the user come back and access his account, the token is expired and he could not see any of his details.



Following is the code to generate token while login:



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
}


Now to decode and match the token following function is used:



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()
}


}



I am not able to detect what I am missing. Please look into the code and guide me what should I do in this case.







go jwt gin






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 at 7:10









Amandeep kaur

327210




327210












  • What is your question? If a token has expired - it only means that it has expired, the expiration time is in the past.
    – zerkms
    Nov 13 at 7:37










  • @zerkms I have set the expiration time to 1 year. The point is it expires when I re-install my go app, which is wrong because neither expiration time is in the past nor the user logged out.
    – Amandeep kaur
    Nov 13 at 8:25










  • "The point is it expires" --- if you set expiration time of a JWT token to one year then it would expire in one year. Otherwise please define what you mean "it expires".
    – zerkms
    Nov 13 at 9:26












  • Actually it is not expired but it is not validated after installing the app.
    – Amandeep kaur
    Nov 13 at 10:18










  • What does "not validated" mean? Which error do you get, which line of code is or is not executed?
    – TommyF
    Nov 13 at 10:23


















  • What is your question? If a token has expired - it only means that it has expired, the expiration time is in the past.
    – zerkms
    Nov 13 at 7:37










  • @zerkms I have set the expiration time to 1 year. The point is it expires when I re-install my go app, which is wrong because neither expiration time is in the past nor the user logged out.
    – Amandeep kaur
    Nov 13 at 8:25










  • "The point is it expires" --- if you set expiration time of a JWT token to one year then it would expire in one year. Otherwise please define what you mean "it expires".
    – zerkms
    Nov 13 at 9:26












  • Actually it is not expired but it is not validated after installing the app.
    – Amandeep kaur
    Nov 13 at 10:18










  • What does "not validated" mean? Which error do you get, which line of code is or is not executed?
    – TommyF
    Nov 13 at 10:23
















What is your question? If a token has expired - it only means that it has expired, the expiration time is in the past.
– zerkms
Nov 13 at 7:37




What is your question? If a token has expired - it only means that it has expired, the expiration time is in the past.
– zerkms
Nov 13 at 7:37












@zerkms I have set the expiration time to 1 year. The point is it expires when I re-install my go app, which is wrong because neither expiration time is in the past nor the user logged out.
– Amandeep kaur
Nov 13 at 8:25




@zerkms I have set the expiration time to 1 year. The point is it expires when I re-install my go app, which is wrong because neither expiration time is in the past nor the user logged out.
– Amandeep kaur
Nov 13 at 8:25












"The point is it expires" --- if you set expiration time of a JWT token to one year then it would expire in one year. Otherwise please define what you mean "it expires".
– zerkms
Nov 13 at 9:26






"The point is it expires" --- if you set expiration time of a JWT token to one year then it would expire in one year. Otherwise please define what you mean "it expires".
– zerkms
Nov 13 at 9:26














Actually it is not expired but it is not validated after installing the app.
– Amandeep kaur
Nov 13 at 10:18




Actually it is not expired but it is not validated after installing the app.
– Amandeep kaur
Nov 13 at 10:18












What does "not validated" mean? Which error do you get, which line of code is or is not executed?
– TommyF
Nov 13 at 10:23




What does "not validated" mean? Which error do you get, which line of code is or is not executed?
– TommyF
Nov 13 at 10:23

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53275636%2fjwt-token-expired-when-go-app-is-installed%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53275636%2fjwt-token-expired-when-go-app-is-installed%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents