I use Golang Beego's package session. When user is logged in - session is created on a server-side and client gets a cookie. For example, expiration date for both session and cookie is 10 sec. I send requests to the server often enough, but still after some seconds (even less than 10) I'm being logged out - that's bad.
Here is a small working example:
package main
import (
"fmt"
"net/http"
"github.com/astaxie/beego/session"
)
var globalSessions *session.Manager
func sessionExists(w http.ResponseWriter, r *http.Request) bool {
sess, err := globalSessions.SessionStart(w, r)
defer sess.SessionRelease(w)
if err != nil {
fmt.Println("Error to start session: " + err.Error())
return false
}
if sessUsername := sess.Get("username"); sessUsername == nil {
return false
}
return true
}
func login(w http.ResponseWriter, r *http.Request) {
sess, err := globalSessions.SessionStart(w, r)
defer sess.SessionRelease(w)
if err != nil {
fmt.Println("Error to start session: " + err.Error())
return
}
sess.Set("username", "user")
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func handler(w http.ResponseWriter, r *http.Request) {
if !sessionExists(w, r) {
fmt.Fprintf(w, "NOT logged in")
} else {
fmt.Fprintf(w, "Logged in")
}
}
func main() {
globalSessions, _ = session.NewManager("memory", &session.ManagerConfig{
CookieName: "msessionid",
EnableSetCookie: true,
Gclifetime: 2,
Maxlifetime: 10,
CookieLifeTime: 10})
go globalSessions.GC()
http.HandleFunc("/", handler)
http.HandleFunc("/login", login)
err := http.ListenAndServe("0.0.0.0:9998", nil)
if err != nil {
fmt.Println("Can't start HTTP listener")
}
}
.. launch it and go to localhost:9998/login
- you will see Logged in
and will be redirected to the main page. Refresh it every second - after some seconds you'll get a NOT logged in
response. I was thinking every request will update session's expiration date on a server-side.
What am I missing? Or this is a bug in a session package?
package hjwt
import (
"fmt"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/hzwy23/hcloud/logs"
)
var (
key []byte = []byte("-jwt-hzwy23@163.com")
)
// json web token
func GenToken() string {
claims := &jwt.StandardClaims{
NotBefore: int64(time.Now().Unix()),
ExpiresAt: int64(time.Now().Unix() + 1000),
Issuer: "hzwy23",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(key)
if err != nil {
logs.Error(err)
return ""
}
return ss
}
// Verify that token is valid
func CheckToken(token string) bool {
_, err := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
fmt.Println("parase with claims failed.", err)
return false
}
return true
}
// Next, add the filter before the beego starts. The filter code is as follows:
beego.InsertFilter("/platform/*", beego.BeforeRouter, func(ctx *context.Context) {
cookie, err := ctx.Request.Cookie("Authorization")
if err != nil || !hjwt.CheckToken(cookie.Value) {
http.Redirect(ctx.ResponseWriter, ctx.Request, "/", http.StatusMovedPermanently)
}
})
// In this process, you need to set the JSON web token value to cookies, where the cookies method is set as follows in.Golang:
token := hjwt.GenToken()
cookie := http.Cookie{Name: "Authorization", Value: token, Path: "/", MaxAge: 3600}
http.SetCookie(w, &cookie)
this is Example https://github.com/nan1888/beego_jwt