Reputation: 257
On my local machine I have running apache server(php,mysql) and simple websocket server (c++). Now i'am trying to make some kind of user authorization with tokens. After some searching on internet i decided to stick to this:
- When the client-side code decides to open a WebSocket, it contacts the HTTP server to obtain an authorization “ticket”.
- The server generates this ticket. It typically contains some sort of user/account ID, the IP of the client requesting the ticket, a timestamp, and any other sort of internal record-keeping you might need.
- The server stores this ticket (i.e. in a database or cache), and also returns it to the client.
- The client opens the WebSocket connection, and sends along this “ticket” as part of an initial handshake.
- The server can then compare this ticket, check source IPs, verify that the ticket hasn’t been re-used and hasn’t expired, and do any other sort of permission checking. If all goes well, the WebSocket connection is now verified.
Does solution above mean that database must be quered 2 times? First in steps 2 and 3, after users successfully log and php generates ticket and put it into database. Second in step 5, when (this time websocket server) must check this ticket by quering the same database again?
Upvotes: 1
Views: 1475
Reputation: 3884
Not only is the database used twice, as you described, but it MUST. This is how you establish trust when you are involving an untrusted client out on the Web. You store the information in a secure way, and then you later validate the information in a secure way.
It is important that the token be encrypted, otherwise it could be manipulated as it travels over the Web.
For example, if you encrypt the token with a private key, then when it comes back, only the public key can decrypt it. So if that succeeds, you know the token is yours and has not been tampered with.
Upvotes: 1