user2288650
user2288650

Reputation: 450

Using sec-websocket-protocol for authentication

I have a php websocket based application where the websocket is the core. Would it be a good idea to use sec-websocket-protocol for authentication.

This is my plan.

User logins using there credentials and I use php sessions to track the user between pages.

Now when user initiates the application a random token is generated and stored in Database which is then passed in the header when websocket is initiated. The header looks kind of

Cache-Control:no-cache
Connection:Upgrade 
Host:tonywilk.no-ip.org:12352    
Origin:http://********.com:port 
Pragma:no-cache    
Sec-WebSocket-Key:DMF3ByMTLq+cp7AyMN0qUA== 
Sec-WebSocket-Protocol:**Token**      **<-- browser sends token 
Sec-WebSocket-Version:13 
Upgrade:websocket

I use the token to verify the user and send server respons with handshake

Connection:Upgrade
Sec-WebSocket-Accept:L6wqtsHk6dzD+kd9NCYT6Wt7OCU=
Sec-WebSocket-Protocol: **Token**               <-- server replies ok
Upgrade:WebSocket

Is this a good idea or is there a better way to do it

Upvotes: 6

Views: 3820

Answers (2)

Alcalyn
Alcalyn

Reputation: 1589

I'm using RatchetPHP for my websocket application.

I can't pass headers when opening a websocket connection, so I pass an OAuth2 token to the websocket uri. It looks like this:

new Websocket('ws://localhost:8482?access_token=XXX')

If you can easily retrieve query parameters in your websocket application, this is something you could try.

This is the trick I'm using in Sandstone: https://eole-io.github.io/sandstone/authentication.html

Upvotes: 0

galkin
galkin

Reputation: 5519

You should use Authorization header for authentication.

Using Sec-WebSocket-Protocol header for authentication is bad idea, because it changes the header meaning:

The |Sec-WebSocket-Protocol| header field is used in the WebSocket
opening handshake. It is sent from the client to the server and back from the server to the client to confirm the subprotocol of the
connection. This enables scripts to both select a subprotocol and be sure that the server agreed to serve that subprotocol. (c) RFC 6455 – The WebSocket Protocol

Upvotes: -1

Related Questions