Websocket, Angular 2 and JSON Web token Authentication

后端 未结 3 2106
死守一世寂寞
死守一世寂寞 2021-01-31 18:58

My Angular 2 app (coded in typescript) has a simple authentication scheme:

  • User logs in:
  • Server returns JSON Web Token (JWT) abc123...
  • <
3条回答
  •  不思量自难忘°
    2021-01-31 19:15

    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){/*...*/}
    

提交回复
热议问题