使用gorilla-toolkit在golang中创建会话(Session)的go-endpoints。

huangapple go评论88阅读模式
英文:

golang go-endpoints Session using gorilla-toolkit

问题

我正在尝试实现会话处理,并将其与go-endpoints包结合使用!

我使用的用于处理会话的包是Gorilla Sessions(github.com/gorilla/sessions),我需要一些帮助..

我能够将一个cookie存储到客户端..当我调用端点时,可以看到cookie被发送到服务器。

问题是,当我尝试从会话存储中获取会话值时,无法获取到cookie..似乎endpoints包会剥离http.Request中的额外内容或其他什么东西..?

我尝试获取cookie的位置是在Server.go的以下代码中:

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request){

     var store = sessions.NewCookieStore([]byte("secret123"));

     session, _ := store.Get(r, "session-name");

     // 获取之前的闪存(如果有)。

     c.Infof("foo value is : %v",r.Cookies());

     if flashes := session.Flashes(); len(flashes) > 0 {

     // 只是打印闪存的值。

     c.Infof("this is the testing post message with cookie from the ServeHTTP    : 
      %v",flashes);
      } 

      else {

      // 设置一个新的闪存。

      session.AddFlash("Hello, flash messages world!")

      c.Infof("No flashes found.");

      }

      session.Save(r, w)

      }

我得到的是一个空数组.... 使用gorilla-toolkit在golang中创建会话(Session)的go-endpoints。

有人有线索吗?

谢谢!!!!

英文:

I'm trying to implement Session handling and combine it with the go-endpoints package !

The package that i use to handle the session is Gorilla Sessions (github.com/gorilla/sessions), i would like some help..

I'm able to store a cookie to the client .. and when i call the endpoints is can see that the cookie is sent to the server.

The problem while i try to get the Session values from the Session storage while the api is called, i cant get threw to the cookie .. it seams that the endpoints package strip the http.Request from extra content or something .. ?

The place that i try to get the cookie is in the Server.go at the

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request){

     var store = sessions.NewCookieStore([]byte("secret123"));

     session, _ := store.Get(r, "session-name");

     // Get the previously flashes, if any.

     c.Infof("foo value is : %v",r.Cookies());

     if flashes := session.Flashes(); len(flashes) > 0 {

     // Just print the flash values.

     c.Infof("this is the testing post message with cookie from the ServeHTTP    : 
      %v",flashes);
      } 

      else {

      // Set a new flash.

      session.AddFlash("Hello, flash messages world!")

      c.Infof("No flashes found.");

      }

      session.Save(r, w)

      }

what i get is a empty array .... 使用gorilla-toolkit在golang中创建会话(Session)的go-endpoints。

someone has a lead ?

THANKS !!!!!

答案1

得分: 1

好的,我会为你翻译以下内容:

好的,我想我对go-endpoints的整体理念有了错误的理解..我对golang还是比较新(大约一年)..

我想写一些关于我发现的内容以及如何保护我的API的东西。

第一步是按照go-endpoints包的说明注册和发现API,网址是:https://github.com/GoogleCloudPlatform/go-endpoints。这个包是最接近使用Java或Python的Google App Engine端点的包。

现在,假设API已经在线并且可以被发现。
如果我们不使用oauth2来保护API,它们将被发现并授予所有用户访问权限..这是我只想在我的公共API中批准的事情,而不是在我的私有API中..所以我尝试使用gorilla session来解决我的问题..

我所做的是尝试通过包装所有路由调用的中间件来监听传入的API调用,路径为"/_ah/api/....",你能想象..我花了很长时间才明白这个路径是保留给Google API的,我不能做我想做的事情..最终..我明白了..虽然有点晚...

所以,重点是,在公开API并为其命名后,你应该使用info.ClientIds和info.Scopes。

代码示例 ---->

const (
dummyClientID = "google appengine client id" 
dummyScope1   = "https://www.googleapis.com/auth/plus.login"
dummyScope2   = "https://www.googleapis.com/auth/plus.me"
dummyScope3   = "https://www.googleapis.com/auth/userinfo.email"
dummyScope4   = "https://www.googleapis.com/auth/userinfo.profile"
dummyAudience = "people"
)

var (
emptySlice = []string{}
clientIDs  = []string{dummyClientID}  // 这是项目的clientId
scopes     = []string{dummyScope1,dummyScope2,dummyScope3,dummyScope4} // 这些是用户必须批准的req oauth2 scopes。
audiences  = []string{dummyAudience} // 这只适用于Android!
)

info := manageApi.MethodByName("GetBusinessById").Info()
info.Name, info.HTTPMethod, info.Path, info.Desc = "GetBusinessById", "POST","GetBusinessById", "Get the business if bid is sent."
info.ClientIds, info.Scopes = clientIDs, scopes

现在剩下的就是在API函数中创建一个endpoint.NewContext并请求适当的范围来获取user.User..

func (ms *ManageService) GetBusinessById(r *http.Request, req *JsonInGetBusinessById, resp *JsonOutEditBusiness) error {
    // 通过bid获取业务。
    DalInst := ManageDataAccessLayer.DALManagerFactory()

    context := endpoints.NewContext(r)

    u,err := context.CurrentOAuthUser("https://www.googleapis.com/auth/userinfo.email")
    if err != nil {
        return err
    }else {
        var businessObj = DalInst.GetBusinessByBid(context, req.BidStr)

        resp.BidStr = u.Email // 仅用于测试,看看客户端是否经过身份验证并且我们可以获取客户端的电子邮件..

        resp.NameStr = businessObj.NameStr
        resp.AddressStr = businessObj.AddressStr
        resp.DescriptionStr = businessObj.DescriptionStr
        resp.DescriptionTwo = businessObj.DescriptionTwo
        resp.PhoneNumberStr = businessObj.PhoneNumberStr

        return nil
    }
}

好的..希望我解释清楚了一些事情!

英文:

Ok sooo i got the hole idea of the go-endpoints wrong i guess ..
Im pretty new to golang (~year)..

i wanted to write something about what i have found and how did a secure my api's.

First step will be to follow the go-endpoints package instructions about how to register and discover the api's at : https://github.com/GoogleCloudPlatform/go-endpoints ,This package is the closest package there is to google app engine endpoints using Java or Python ..

Now, lets say the api are online and discoverable.
if we wont use oauth2 to secure the api's they will be discoverable and grant access for all users .. and that something i would like to approve only in my public api's and not in my private .. so i tried gorilla session thinking it will solve my problem ..

What i did was trying to listen to incoming api calls by wrapping withe middleware all the rout calles passing "/_ah/api/....", can you imagine .. took my forever to understand that this path is reserved to google api and that i can do what i was trying .. eventually .. i got it .. batter later then ever ...

soo to the point, after exposing the api's giving it names and all you should use the info.ClientIds, info.Scopes.

code example ---->

> const (
> dummyClientID = "google appengine client id"
> dummyScope1 = "https://www.googleapis.com/auth/plus.login"
> dummyScope2 = "https://www.googleapis.com/auth/plus.me"
> dummyScope3 = "https://www.googleapis.com/auth/userinfo.email"
> dummyScope4 = "https://www.googleapis.com/auth/userinfo.profile"
> dummyAudience = "people"
> )

> var (
> emptySlice = []string{}
> clientIDs = []string{dummyClientID} // this is the clientId of the project
> scopes = []string{dummyScope1,dummyScope2,dummyScope3,dummyScope4} // >this are the req oauth2 scopes that the user hase to approve.
> audiences = []string{dummyAudience} // this is only for android !
> )

> info := manageApi.MethodByName("GetBusinessById").Info()
> info.Name, info.HTTPMethod, info.Path, info.Desc = "GetBusinessById", >"POST","GetBusinessById", "Get the business if bid is sent."
> info.ClientIds, info.Scopes = clientIDs, scopes

now all that is left to do is in the api function creating a endpoint.NewContext and ask the appropriate scope to get user.User ..

> func (ms *ManageService) GetBusinessById(r *http.Request, req >*JsonInGetBusinessById, resp *JsonOutEditBusiness) error {
> // go get the business by bid.
> DalInst := ManageDataAccessLayer.DALManagerFactory()

> context := endpoints.NewContext(r)

> u,err := >context.CurrentOAuthUser("https://www.googleapis.com/auth/userinfo.email")
> if err != nil {
> return err
> }else {

> var businessObj = DalInst.GetBusinessByBid(context, req.BidStr)

> resp.BidStr = u.Email //just for testing to see if the client is auth and >we can get client Email..

> resp.NameStr = businessObj.NameStr
> resp.AddressStr = businessObj.AddressStr
> resp.DescriptionStr = businessObj.DescriptionStr
> resp.DescriptionTwo = businessObj.DescriptionTwo
> resp.PhoneNumberStr = businessObj.PhoneNumberStr

> return nil
> }

>ok .. hope i made some things clear !

huangapple
  • 本文由 发表于 2015年3月19日 16:49:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/29140239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定