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

wn0112 · · 5900 次点击
gin不熟,但是大概思路应该是共通的。 你应该是需要一个sesson组件和一个user组件,里面应该提供合适的中间件 你的代码太原始了,而且居然没有记录登录前的地址…… 以我的代码为例 //middlewares.go MiddlewareMemberLoginOrRedirect = MemberLoginRedirector.Middleware(membermodule.Member) MiddlewareMemberLoginReqiured = user.LoginRequiredMiddleware(membermodule.Member, nil) //userrouter.go var UserMiddlewares = func() middleware.Middlewares { return middleware.Middlewares{ middlewares.MiddlewareInstallMemberSession, middlewares.MiddlewareMemberLoginOrRedirect, } } //routers.go Router.StripPrefix("/usercenter/user"). Use(UserMiddlewares()...). Handle(RouterUser)
#6
更多评论
网上看到这个例子,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