gin 框架,登录验证功能,然后每个接口都需要鉴权,用哪个包?

wn0112 · · 5898 次点击
[github.com/gin-contrib/sessions](github.com/gin-contrib/sessions)这个中间件可以帮助 到你 ~~~ go package main import ( "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() store := cookie.NewStore([]byte("secret")) r.Use(sessions.Sessions("session_id", store)) r.GET("/login", func(c *gin.Context) { session := sessions.Default(c) //登录成功后设置一下状态 // AuthMiddleWare里可以判断是否登录成功,使用session.Get("status") session.Set("status", true) session.Save() c.JSON(200, gin.H{"status": true}) }) r.Run(":8000") } ~~~
#8
更多评论
网上看到这个例子,cookie 的 value 要自己填吗?比如用SHA256加密 用户名密码得到的字串? ```go package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) func main() { r := gin.Default() r.Use(AuthMiddleWare()) { r.GET("/login", func(c *gin.Context) { cookie := &http.Cookie{ Name: "session_id", Value: "onion", //这个是value要自己生成??规则自定就可以? Path: "/", HttpOnly: true, } http.SetCookie(c.Writer, cookie) c.String(http.StatusOK, "登录成功") }) r.GET("/home", AuthMiddleWare(), func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"data": "hello world"}) }) } r.Run() // listen and serve on 0.0.0.0:8080 } func AuthMiddleWare() gin.HandlerFunc { return func(c *gin.Context) { fmt.Println(c.Request.URL.String()) if cookie, err := c.Request.Cookie("session_id"); err == nil { value := cookie.Value fmt.Println(value) if value == "onion" { c.Next() return } } if url := c.Request.URL.String(); url == "/login" { c.Next() return } c.JSON(http.StatusUnauthorized, gin.H{ "error": "Unauthorized", }) c.Abort() return } } ```
#2