Gorilla websocket 带有 cookie 认证

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

Gorilla websocket with cookie authentication

问题

这是我的设置:我正在使用Negroni和Gorilla构建一个带有用户登录功能的服务,用户登录后会获得一个会话cookie,服务器使用该cookie来授权受保护的端点。其中一个受保护的端点允许用户/客户端与服务器建立WebSocket连接,代码如下:

app := negroni.New()

r := mux.NewRouter()

r.HandleFunc("/auth/connection", func(rw http.ResponseWriter, req *http.Request) {
    // 使用 req.Cookie("session_id") 授权请求

    // 创建 WebSocket
    conn, err := upgrader.Upgrade(rw, req, nil)
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    // 处理逻辑...
})

app.UseHandler(r)

app.Run(":3000")

然而,req.Cookies() 总是为空,这意味着我无法对 /auth/connection 进行授权。我几乎可以确定这不是WebSocket客户端的问题(如果你感兴趣,我正在使用这个Python包进行测试:https://github.com/liris/websocket-client)。我对WebSocket的身份验证方法是否正确?

非常感谢任何帮助和建议!

英文:

Here's my setup: I'm building a service (using Negroni and Gorilla) with user login, where upon login, the user gets a session cookie which the server uses to authorize protected endpoints. One of the protected endpoints allows the user/client to open a websocket with the server, like so:

app := negroni.New()

r := mux.NewRouter()

r.HandleFunc("/auth/connection", func(rw http.ResponseWriter, req *http.Request) {
    // authorize request using req.Cookie("session_id")

    // create websocket
    conn, err := upgrader.Upgrade(rw, req, nil)
    if err != nil {
	    panic(err)
    }
    defer conn.Close()

    // do stuff...
})

app.UseHandler(r)

app.Run(":3000")

However, req.Cookies() is always empty, meaning I can't authorize any requests to "/auth/connection" -- and I'm almost positive it is not a problem with the websocket client (if you're curious, I'm testing it using this Python package: https://github.com/liris/websocket-client). Am I approaching authentication of a websocket correctly?

Any help/advice would be greatly appreciated!

答案1

得分: 2

服务器在进行WebSocket握手时,会将其视为普通的HTTP请求,直到调用Upgrade方法。使用与普通HTTP请求相同的身份验证方式。

在具有auth注释的代码行中,Gorilla包没有起作用。

英文:

The server handles the WebSocket handshake as a normal HTTP request up to the point where Upgrade is called. Use whatever authentication you would use for normal HTTP requests.

The Gorilla package is not in play at the line of code with the auth comment.

huangapple
  • 本文由 发表于 2015年3月29日 08:27:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/29324251.html
匿名

发表评论

匿名网友

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

确定