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

wn0112 · 2019-04-08 11:14:42 · 6085 次点击
更多评论

网上看到这个例子,cookie 的 value 要自己填吗?比如用SHA256加密 用户名密码得到的字串?

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

Value 肯定要自己填写,你提到的用 SHA256 加密用户名密码也可以的,自己定义。 因为 http 是无状态的,你服务端需要保存这个字符串及其对应的用户,用户请求时带上这个 cookie,才能知道是请求用户是否登录、有没有权限等

#3