How to authenticate a user when using web sockets?

What's the best way, in your opinion, to check user rights of user to certain actions when using web sockets?
I found a way, but as for me, it's terrible (in the specific example used yii2 and Ratchet as a web socket server.):
/**
 * Open session and db connections. Returns the 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('User does not exist.');
}
 Yii::$app->set('request', new Request());
 if (!Yii::$app->user->login($user)) {
 throw new Exception('User does not exist.');
}
 return $user;
}

/**
 * Session and Close db connections. The User logs out.
*/
 private function offUser()
{
Yii::$app->user->logout();
Yii::$app->session->close();
Yii::$app->db->close();
 }


How to "user" is more correct, or at least tell me how to get session of the current user?
June 14th 19 at 20:32
1 answer
June 14th 19 at 20:34
I guess the token. When connecting the transmitted http headers. There can be Bearer to pass. You and JWT token to use I guess. The essence is important: connection authorization by token.

Find more questions by tags PHPSessionsWebSocket