dongtao1262 2017-10-06 08:14
浏览 38

比戈到期日期的Golang会话

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?

  • 写回答

1条回答 默认 最新

  • douou6696 2017-10-09 06:14
    关注
           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

    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入