简体   繁体   English

为什么 Laravel Sanctum append token key 到 plainTextToken?

[英]Why does Laravel Sanctum append token key to the plainTextToken?

Referring to the following code from Sanctum:参考 Sanctum 中的以下代码:

public function createToken(string $name, array $abilities = ['*'])
    {
        $token = $this->tokens()->create([
            'name' => $name,
            'token' => hash('sha256', $plainTextToken = Str::random(40)),
            'abilities' => $abilities,
        ]);

        return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
    }

Source: https://github.com/laravel/sanctum/blob/31fbe6f85aee080c4dc2f9b03dc6dd5d0ee72473/src/HasApiTokens.php#L44-L53来源: https://github.com/laravel/sanctum/blob/31fbe6f85aee080c4dc2f9b03dc6dd5d0ee72473/src/HasApiTokens.php#L44-L53

Why does Sanctum append $token->getKey() to the $plainTextToken ?为什么 Sanctum append $token->getKey()$plainTextToken In other words, what is the purpose of the $token->getKey() part?换句话说, $token->getKey()部分的目的是什么? Is it used during authentication as a key to retrieve the encrypted token string and compare it using Hash::check or something?它是否在身份验证期间用作检索加密令牌字符串并使用Hash::check或其他方式进行比较的密钥?

I have another question: The migration that creates the personal_access_tokens table indicates that the token column is unique.我还有一个问题:创建 personal_access_tokens 表的迁移表明 token 列是唯一的。 However, in the above code I can see that the value stored in the token column is just a hashed value of a random string hash('sha256', $plainTextToken = Str::random(40)) .但是,在上面的代码中,我可以看到存储在令牌列中的值只是随机字符串hash('sha256', $plainTextToken = Str::random(40))的哈希值。 Does the hash function always return unique values so that it doesn't violate the unique constraint? hash function 是否始终返回唯一值以便不违反唯一约束?

My first thought was that the $token->getKey() should be appended to the encrypted string to make it unique.我的第一个想法是$token->getKey()应该附加到加密字符串以使其唯一。 But I think this is not the case.但我认为情况并非如此。

Sanctum createToken function creates a string of 40 characters, Sanctum createToken function创建一个40个字符的字符串,

Str::random(40)

then hashs it but before hashing, stores it into a variable $plainTextToken .然后对其进行哈希处理,但在进行哈希处理之前,将其存储到变量$plainTextToken中。

hash('sha256', $plainTextToken = Str::random(40))

Hashed token goes to the database and un-hashed token returns to user.散列令牌进入数据库,未散列令牌返回给用户。

 $token = $this->tokens()->create([
        'name' => $name,
        'token' => hash('sha256', $plainTextToken = Str::random(40)),
        'abilities' => $abilities,
    ]);

Return the un-hashed part to the user with primary key of database record.使用数据库记录的主键将未散列的部分返回给用户。 the primary key helps to find the token quickly.主键有助于快速找到令牌。 if you remove primary key it will work too.如果您删除主键,它也会起作用。

 return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken)

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

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