My Angular 2 app (coded in typescript) has a simple authentication scheme:
abc123...
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){/*...*/}