如何向经过身份验证的路由添加持有者令牌身份验证

How can I add bearer token authentication to authenticated routes

提问人:Sharuhen 提问时间:11/8/2023 更新时间:11/8/2023 访问量:43

问:

实际上,我已经将 jwt 持有者令牌身份验证添加到用 Express nodejs 编写的 API 中。在我的 mern 项目中,甚至在 postman 中的测试中,token 已成功添加到标头中。但是我已经在php curl中创建了项目仪表板部分,这里在php curl令牌中没有传递到经过身份验证的路由。我的身份验证.js代码是:

function auth(req, res, next) {
    var token = req.headers['authorization'] || req.cookies.jwtPW;
      if(!token && req.query.token){
         token = req.query.token;
         }  
      try {   
       if (!token) return res.status(401).json({ errorMessage: "Unauthorized Token" });
           jwt.verify(token,process.env.SECRETKEY,(err,payload) => {
        if (err) {
          console.log('JWT Verification:', err);
          return res.status(401).json({ error: "You must have logged in" });
          }
          }
         }
     }  

当我们使用用户名和密码点击登录端点时,它会生成新的令牌,并且令牌以 json 格式返回 php 文件 response.in 我获取了这个令牌值并将令牌值存储在变量 $token 中,然后我将此令牌传递给经过身份验证的路由的标头。但是当我运行这个文件时,它总是抛出错误:你必须登录 2”。给定以下 auth.js 代码行:

   jwt.verify(token,process.env.SECRETKEY,(err,payload) => {
      if (err) {
        console.log('JWT Verification:', err);
        return res.status(401).json({ error: "You must have logged in 2" });
      }                                 
                                                                                                                                 I have added query params to login and authenticated route.

这是php代码:

<?php
   $loginApiUrl = "http://localhost:8080/api/users/login?token=token";
   $username = 'SulemanSohail';
   $password = '3456789';

   $data = [
       'username' => $username,
       'password' => $password,
         ];

   $ch = curl_init($loginApiUrl);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
   $response = curl_exec($ch);

 if (curl_errno($ch)) {
      echo 'cURL error: ' . curl_error($ch);
      exit;
      }
  curl_close($ch);
  $responseData = json_decode($response, true);
  if (json_last_error() === JSON_ERROR_NONE) {
      
     if (isset($responseData['token'])) {
        $token = $responseData['token'];
        echo 'Token: ' . $token;
       } else {
          echo 'Login failed. No token received.';
         }
    } else{

        }

   function isTokenValid($token) {
      $tokenData = explode('.', $token);
      if (count($tokenData) !== 3) {
        // Token format is invalid
         return false;
        }

      list(, $payload) = $tokenData;
      $decodedPayload = json_decode(base64_decode($payload), true);
      if (isset($decodedPayload['exp'])) {
        $expirationTime = $decodedPayload['exp'];
        $currentTime = time();
        return $expirationTime > $currentTime;
        } else {
          // Token does not have an expiration time
          return true;
               }
         }

      if (isTokenValid($token)) {
           echo 'Token is valid.';
          } else{
           echo 'Token is invalid or has expired.';
            }

      $apiUrl = "http://localhost/api/users/all?token=$token"; // Replace with the actual API URL

      $curl = curl_init();

      curl_setopt($curl, CURLOPT_URL, $apiUrl); // Set the URL
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
      curl_setopt($curl, CURLOPT_HTTPHEADER, array(
     'Authorization: Bearer ' . $token, // Set the Authorization header with the token
      'Content-Type: application/json' // Set the content type header to JSON if required
       ));

      $response = curl_exec($curl);

                                                                                                       I tried different soltutions but couldn't accomplish task , if any body help me on it.

我尝试了不同的解决方案,令牌已成功生成,我们将其存储在可变中并将其传递给经过身份验证的路由,但我不知道经过身份验证的路由没有接受令牌,因为它是身份验证中间件抛出错误jwtverification在节点服务器中失败,在浏览器中显示错误“您必须登录2”。(我在 mern 和 postmam API 中的 php 中面临的这个问题工作正常)。 我无法确切地了解为什么会发生这种情况,我将相同的 SECRETKEY 传递给登录 api 和 auth.js 中间件。

node.js 表示 php-curl

评论

0赞 Yuvaraj M 11/8/2023
您是否在 postman 中传递了 Bearer 关键字?
0赞 Sharuhen 11/8/2023
是的,我愿意。实际上,无论我是否在邮递员 cookie 中传递 Bearer 关键字,都会自动添加 cookie。但是在我的 mern 项目中,我添加了这个持有者令牌来验证路由: 'Authorization': .当我在 php 项目中使用我的 API 时,mern 项目和邮递员一切都很顺利,只是出现了问题Bearer ${localStorage.getItem('token')}
0赞 Sharuhen 11/8/2023
嗨,我忘记了在将令牌传递给 jwt 之前先拆分令牌以验证它。我进行了以下更改:var token = req.headers['authorization'] ||req.cookies.jwtPW;if (req.headers.authorization) { token = req.headers.authorization.split(' ')[1];现在身份验证也适用于php项目。谢谢
0赞 Yuvaraj M 11/8/2023
这就是我想说的

答: 暂无答案