J
J
John-Galt2017-10-02 20:55:58
PHP
John-Galt, 2017-10-02 20:55:58

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();
    }

How do you think it is more correct to get the "user" or at least tell me how to get the session of the current user more correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Balin, 2017-10-12
@krocos

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 question

Ask a Question

731 491 924 answers to any question