gpt4 book ai didi

session - 比戈到期日期的Golang session

转载 作者:数据小太阳 更新时间:2023-10-29 03:24:13 28 4
gpt4 key购买 nike

我用的是Golang Beego的套餐。当用户登录时-会话是在服务器端创建的,客户端会得到一个cookie。例如,会话和cookie的到期日期都是10秒。我经常向服务器发送请求,但在几秒钟(甚至不到10秒)之后,我还是被注销了——这很糟糕。
下面是一个小的工作示例:

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

…启动它并转到 localhost:9998/login-您将看到 Logged in,并将被重定向到主页面。每秒刷新一次-几秒钟后,您将得到 NOT logged in响应。我想每个请求都会在服务器端更新会话的到期日期。
我错过了什么?或者这是会话包中的错误?

最佳答案

       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)

这是 https://github.com/nan1888/beego_jwt

关于session - 比戈到期日期的Golang session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46601270/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com