CakePHP 3:如何在注册后自动登录用户

CakePHP 3: How to automatically log a user in after registration

我试图让用户在注册后立即使用 CakePHP 3,但没有成功。这就是我正在做的事情:

function register(){
    // ....
    if($result = $this->Users->save($user)){
        // Retrieves corresponding user that was just saved
        $authUser = $this->Users->get($result->id);

        // Log user in using Auth
        $this->Auth->setUser($authUser);

        // Redirect user
        $this->redirect('/users/account');
    }
}

我想发布这个问题让我大开眼界,找到了解决办法。这就是我为了让它工作所做的......如果有更好的方法,我很乐意改变它......

function register(){
    // .... Default CakePHP generated code

    if($result = $this->Users->save($user)){
        // Retrieve user from DB
        $authUser = $this->Users->get($result->id)->toArray();

        // Log user in using Auth
        $this->Auth->setUser($authUser);

        // Redirect user
        $this->redirect(['action' => 'account']);
    }
}

CakePHP 3.8 × cakephp/authentication 更新。

Any place you were calling AuthComponent::setUser(), you should now use setIdentity():

// Assume you need to read a user by access token
$user = $this->Users->find('byToken', ['token' => $token])->first();

// Persist the user into configured authenticators.
$this->Authentication->setIdentity($user);

来源:/authentication/1/en/migration-from-the-authcomponent.html#checking-identities