My Angular 2 app (coded in typescript) has a simple authentication scheme:
abc123...
Authorization
headerNow I'd like to add websockets. I'm wondering how to authenticate the user there. Since I don't control which headers are sent to the websocket server (WS), I cannot send the JWT.
My idea so far (not yet implemented):
let sock = new WebSocket('wss://example.com/channel/');
open
event on the socket. Once the socket is open: type='auth'
payload='JWT_VALUE'
auth
. Once that is received, server reads the payload, validates JWT_VALUE
and sets an isAuthenticated
flag isAuthenticated
sends any other type of message, server disconnects the socket2 problems: server resources can be taken up by clients who connect but never send the JWT, and a cleaner solution would block the handshake if the client is not authenticated.
Other ideas:
new WebSocket('wss://example.com/channel/<JWT>/')
How do you authenticate clients on websockets? Assume the user already logged in via HTTP and that the Angular 2 app has a JWT token.
I settled on the following protocol:
1. Client logs into the site and receives an authentication token (JSON Web Token)
GET /auth { user: 'maggie', pwd: 'secret' } // response { token: '4ad42f...' }
2. Authenticated client requests a websocket connection ticket
GET /ws_ticket Authorization: Bearer 4ad42f... // response: single-use ticket (will only pass validation once) { ticket: 'd76a55...', expires: 1475406042 }
3. Client opens the websocket, sending the ticket in query param
var socket = new WebSocket('wss://example.com/channel/?ticket=d76a55...');
4. Websocket server (PHP) then validates the ticket before accepting the handshake
/** * Receives the URL used to connect to websocket. Return true to admit user, * false to reject the connection */ function acceptConnection($url){ $params = parse_str(parse_url($url, PHP_URL_QUERY)); return validateTicket($params['ticket']); } /** Returns true if ticket is valid, never-used, and not expired. */ function validateTicket($ticket){/*...*/}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With