Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gorilla websocket with cookie authentication

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!

like image 219
Cody Avatar asked Mar 29 '15 00:03

Cody


People also ask

Can WebSocket set cookie?

You can't set a cookie upon receipt of a webSocket message because it's not an http request. Once the webSocket connection has been established, it's an open TCP socket and the protocol is no longer http, thus there is no built-in way to exchange cookies.

How do I authenticate a WebSocket?

Authentication FlowThe server generates a temporary external authentication token, stores it in the Authentication Cache, and returns it to the client. The client makes a WebSocket handshake request with the external authentication token passed as a query-string parameter in the handshake endpoint URL.

What is Gorilla WebSocket?

GitHub - gorilla/websocket: A fast, well-tested and widely used WebSocket implementation for Go. Skip to content Toggle navigation. Product.


1 Answers

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.

like image 181
Bayta Darell Avatar answered Sep 29 '22 14:09

Bayta Darell