Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

javascript - How to organize authentication in websockets

I have project on php and websocket server, written on C using libwebsockets.

And i have to organize some authentication logic between client side js code and server side.

On php i use sessions with PHPSESSID cookie set on client side after successfull login.

I can access that cookie on websocket server but,

how to compare it with session_id() on server's php side?

question from:https://stackoverflow.com/questions/65883573/how-to-organize-authentication-in-websockets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will need to create an API endpoint for your js on the client side to call and provide the cookie ID to a PHP function. The PHP function with then do the comparison and provided a response to the API call of either validate pass or fail.

i.e

JS calls > https://example.com/api/varifyuser with JSON

{ 
  user_id: 321, 
  session_id: [ENTER PHPSESSID]
}

PHP does comparison and returns

{response:   
  {
    valid_session: true, 
    session_token: 123ad12dasf312af3123, 
    user_id: 321, 
    session_id: 123ABC
  }
}

All comparisons should be handled on the server side to maintain security. Anything done on the client side is exposed to easy interception and vulnerabilities


Basic example of processing the sent key from cookie on PHP server

    if(preg_match("/Sec-WebSocket-Key: (.*)
/", $headers, $match))
        $key = $match[1];

    $comparedKey = $key.'2642975-A114-47DA-95CA-342345685B11';
    $comparedKey = base64_encode(sha1($comparedKey, true));

    $upgrade = "HTTP/1.1 101 Switching Protocols
".
               "Upgrade: websocket
".
               "Connection: Upgrade
".
               "Sec-WebSocket-Accept: $comparedKey".
               "

";

    socket_write($client->getSocket(), $upgrade);
    $client->setHandshake(true);
    return true;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...