简体   繁体   中英

How does laravel check if users are authenticated?

I might not understand the laravel authentication architecture, but it seems to me quite hard to understand how does the Auth::check() function actually work, since it doesn't get any parameter as an input. Precisely, my question, is how does the function know what user is checking?

Actually, the Auth::check() has following code

public function check()
{
    return ! is_null($this->user());
}

The function Auth::user() returns the user instance if any user is logged in or null if none is logged in. So, it's not checking who is logged in but it only checks if any user is logged in or not.

Whenever a user logs in to the application, the Auth::login() function does this at first

$this->updateSession($id = $user->getAuthIdentifier());

This code is self-explanatory, it just updates the session , here $user->getAuthIdentifier() returns the primary key of the logged in user and Auth::updateSession() function simply runs this

$this->session->put($this->getName(), $id);

Here, $this->getName() returns an md5 string which is being used as the key and $id is the logged in user id, so it just puts the user id in the session associated with a key (unique md5 string).

So, actually the Auth::check() triggers the Auth::user() function and that function mainly checks the session for this md5 key and if this key is available in the session then it contains an integer value which is the user id.

The key looks something like this login_82e5d2c56bdd0811318f0cf078b78bfc and it may contain an integer value of user id if any user is logged in.

This is a sample of session data when a user is logged in

array (size=4)
    '_token' => string 'CmHN90G2sVWvejx9r6MMo8AU2dhhV8z9BJQPzATt' (length=40)
    'flash' => 
        array (size=2)
            'old' => array (size=0) empty
            'new' => array (size=0)   empty
        'login_82e5d2c56bdd0811318f0cf078b78bfc' => int 1 <-- current user id
        '_sf2_meta' => 
            array (size=3)
                'u' => int 1391189690
                'c' => int 1391187210
                'l' => string '0' (length=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM