Answer the question
In order to leave comments, you need to log in
How to authorize a user when using web sockets?
What's the best way in your opinion to check user's user permissions for certain actions when using websockets?
I found this way for myself, but in my opinion, it is terrible (in a specific example, yii2 and Ratchet are used as a web socket server.):
/**
* Open session and db connections. Returns connected user.
*
* @throws \Exception
* @param ConnectionInterface $conn
* @return UserAccounts
*/
private function onUser($conn)
{
Yii::$app->session->close();
session_id($conn->WebSocket->request->getCookie(ini_get('session.name')));
Yii::$app->session->open();
Yii::$app->db->open();
if (!($user = UserAccounts::findOne(Yii::$app->session['__id']))) {
throw new Exception('Пользователь не существует.');
}
Yii::$app->set('request', new Request());
if (!Yii::$app->user->login($user)) {
throw new Exception('Пользователь не существует.');
}
return $user;
}
/**
* Close session and db connections. User logs out.
*/
private function offUser()
{
Yii::$app->user->logout();
Yii::$app->session->close();
Yii::$app->db->close();
}
Answer the question
In order to leave comments, you need to log in
I think it's better with a token. When connecting, http headers are transmitted. You can transfer Bearer there. You can probably use a JWT token as well. The very essence is important: connection authorization by token.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question