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

wn0112 · · 5891 次点击
更多评论
网上看到这个例子,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