double0201 2019-06-04 02:40
浏览 124

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

I'm setting up a Vue js/Vuetify website with a PHP Slim Framework API, and tuuopla slim-jwt-auth as a middleware for JWT token authentication. The unprotected routes are working fine but when I try to send axios requests to the protected routes in the API I only got token not found error.

I dont know if the problem is at Vue js, axios or the API configuration. curl and Postman gives the decoded key as expected when acessing the protected route, only the Vue js website gives this errors. To run the API I'm using PHP built-in server: `php -S localhost:8000 -t public/

In any case, the localStorage.getItem("token") does exist, as I tried to print them before every request as well in the interceptor.

Here is a test component :

<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 config(tried with and without the interceptor)

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(a protected and a unprotected sample routes for my tests)

...
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(tried many configurations)

<?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));
    }
]));

The errors when tried to access the api/user route:

  • Chrome console:
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 Response:
{
    "status": "error",
    "message": "Token not found."
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 求差集那个函数有问题,有无佬可以解决
    • ¥15 MATLAB动图问题
    • ¥15 【提问】基于Invest的水源涵养
    • ¥20 微信网友居然可以通过vx号找到我绑的手机号
    • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
    • ¥15 解riccati方程组
    • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
    • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
    • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
    • ¥50 树莓派安卓APK系统签名