简体   繁体   English

laravel如何检查用户是否通过身份验证?

[英]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. 我可能不了解laravel身份验证体系结构,但是在我看来,很难理解Auth::check()函数的实际工作方式,因为它没有获取任何参数作为输入。 Precisely, my question, is how does the function know what user is checking? 准确地说,我的问题是,该功能如何知道用户在检查什么?

Actually, the Auth::check() has following code 实际上, Auth::check()具有以下代码

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. 如果任何用户登录,函数Auth::user()将返回用户实例;如果没有用户登录,则函数返回null。因此,它不检查谁在登录,而仅检查是否有用户登录。

Whenever a user logs in to the application, the Auth::login() function does this at first 每当用户登录到应用程序时, Auth::login()函数都会首先执行此操作

$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 这段代码是不言自明的,它只是更新session ,在这里$user->getAuthIdentifier()返回已登录用户的主键,而Auth::updateSession()函数只是运行此命令

$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). 在这里, $this->getName()返回一个用作keymd5字符串,而$id是已登录的用户ID,因此它将用户ID放在与密钥相关联的会话中(唯一的md5字符串)。

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. 因此,实际上Auth::check()会触发Auth::user()函数,并且该函数主要在会话中检查此md5密钥,如果该key在会话中可用,则它包含一个整数值,即用户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. 密钥看起来像这样的login_82e5d2c56bdd0811318f0cf078b78bfc ,如果有任何用户登录,它可能包含用户ID的整数值。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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