未找到Slim jwt令牌(由axios请求发送)

问题描述 投票:1回答:1

我正在使用PHP Slim Framework API和tuuopla slim-jwt-auth作为JWT令牌认证的中间件来建立Vue js / Vuetify网站。不受保护的路由工作正常,但是当我尝试将axios请求发送到API中的受保护路由时,我只有未找到令牌的错误。

我不知道问题出在Vue js,axios还是API配置。 curl和Postman在访问受保护的路由时按预期方式提供了解码后的密钥,只有Vue js网站给出了此错误。要运行API,我使用的是PHP内置服务器:`php -S localhost:8000 -t public /

无论如何,localStorage.getItem("token")确实存在,因为我也尝试在拦截器中的每个请求之前打印它们。

这里是一个测试组件:

<template>
 <v-btn @click="test">Test</v-btn>
 <v-btn @click="test2">Test</v-btn>
</template>
<script>
  methods: {
    test() {
      axios
        .post("api/user",{},{
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token")}`
            }
          }
        )
        .then(res => console.log(res))
        .catch(err => console.log(err));
    },
    test2() {
      var yourConfig = {
        headers: {
          Authorization: "Bearer " + localStorage.getItem("token")
        }
      };
      axios
        .get("test", yourConfig)
        .then(res => console.log(res))
        .catch(err => console.log(err));
    }
  },
</script>

axios配置(尝试使用拦截器和不使用拦截器)

axios.defaults.baseURL = "http://localhost:8000";
axios.interceptors.request.use(
  config => {
    let token = localStorage.getItem("token");

    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    console.log(token)
    return config;
  },

  error => {
    return Promise.reject(error);
  }
);

Slim index.php(我的测试中受保护和不受保护的示例路径)

...
use Slim\Http\Request;
use Slim\Http\Response;

$app->group('/api', function (\Slim\App $app) {
    $app->get('/user', function (Request $request, Response $response, array $args) {
        return $response->withJson($request->getAttribute('decoded_token_data'));
    });
});
$app->get('/test', function (Request $request, Response $response, array $args) {
    return $response->withJson(["hi"=>"hello"]);
});

// Run app
$app->run();

middleware.php(尝试了许多配置)

<?php
// Application middleware
use Slim\Http\Request;
use Slim\Http\Response;

use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;


$logger = new Logger("slim");
$rotating = new RotatingFileHandler(__DIR__ . "/logs/slim.log", 0, Logger::DEBUG);
$logger->pushHandler($rotating);

$app->add(new \Tuupola\Middleware\JwtAuthentication([
    "secure" => false,
    "logger" => $logger,
    "relaxed" => ["localhost:8080"],
    "attribute" => "decoded_token_data",
    "secret" => "mykey",
    "algorithm" => ["HS256"],
    "rules" => [
        new \Tuupola\Middleware\JwtAuthentication\RequestPathRule([
            // Degenerate access to '/api'
            "path" => ["/api"],
            // It allows access to 'login' without a token
            "passthrough" => [
                "/login_admin"
                //"/login_admin"
            ]
        ])
    ],
    "error" => function ($response, $arguments) {
        $data["status"] = "error";
        $data["message"] = $arguments["message"];
        return $response
            ->withHeader("Content-Type", "application/json")
            ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
    }
]));

[尝试访问api/user路由时的错误:

  • Chrome控制台:
OPTIONS http://localhost:8000/api/user net::ERR_ABORTED 401 (Unauthorized)
Access to XMLHttpRequest at 'http://localhost:8000/api/user' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
  • API响应:
{
    "status": "error",
    "message": "Token not found."
}
php vue.js jwt axios slim
1个回答
0
投票

您是否尝试添加

RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

到您的.htaccess文件?

© www.soinside.com 2019 - 2024. All rights reserved.