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 请完成下列相关问题!
    • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
    • ¥15 求daily translation(DT)偏差订正方法的代码
    • ¥15 js调用html页面需要隐藏某个按钮
    • ¥15 ads仿真结果在圆图上是怎么读数的
    • ¥20 Cotex M3的调试和程序执行方式是什么样的?
    • ¥20 java项目连接sqlserver时报ssl相关错误
    • ¥15 一道python难题3
    • ¥15 牛顿斯科特系数表表示