简体   繁体   English

JWT 和 PHP:验证传递的令牌 (Lcobucci\\JWT)

[英]JWT and PHP: Validating a passed token (Lcobucci\JWT)

I am attempting to learn how to pass a JWT token from ReactJS to my PHP API.我正在尝试学习如何将 JWT 令牌从 ReactJS 传递到我的 PHP API。 I have 2 functions currently: the authentication function to check the username and password and then generate and pass back a token.我目前有两个功能:用于检查用户名和密码的身份验证功能,然后生成并传回令牌。 The generation part seems to work, but when I pass the token back in the Authorization Bearer, I can't get it to validate.生成部分似乎有效,但是当我将令牌传回授权承载中时,我无法对其进行验证。 I am using the Lcobucci\\JWT library.我正在使用 Lcobucci\\JWT 库。

Here is my code:这是我的代码:

 public function attempt_login($input){
            $time = time();
            $token = (new Builder())->issuedBy('https://api.example.com')
            ->permittedFor('https://example.com') 
            ->identifiedBy('4f1g23a12aa', true) 
            ->issuedAt($time) 
            ->canOnlyBeUsedAfter($time + 60) 
            ->expiresAt($time + 3600) 
            ->withClaim('uid',1) 
            ->getToken(); 
            return $token;
    }

    public function find($headers){
        $auth = $headers['Authorization'];
        if (preg_match('/Bearer\s(\S+)/', $auth, $matches)) {
            $token = (new Parser())->parse((string) $matches[1]);
            $data = new ValidationData();
            $data->setIssuer('https://api.example.com');
            $data->setAudience('https://example.com');
            $data->setId('4f1g23a12aa');
            dd($token->validate($data));
        }else{
            dd('nope');
        }
    }

When I dump and die, I always get false.当我倾倒和死亡时,我总是得到错误的。 I am 95% sure I am doing it all wrong, but can anyone help me figure this out?我 95% 确定我做错了,但谁能帮我解决这个问题?

If you are checking for validity right away, you would need to change如果您要立即检查有效性,则需要更改

canOnlyBeUsedAfter($time + 60)

to simply简单地

canOnlyBeUsedAfter($time)

Otherwise you need to wait 60 seconds before it becomes valid.否则您需要等待 60 秒才能生效。

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

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