找不到 Slim jwt 令牌(由 axios 请求发送)
Posted
技术标签:
【中文标题】找不到 Slim jwt 令牌(由 axios 请求发送)【英文标题】:Slim jwt token(sent by axios request) not found 【发布时间】:2019-10-19 13:27:24 【问题描述】:我正在使用php Slim Framework API 和tuuopla slim-jwt-auth 作为 JWT 令牌身份验证的中间件设置 Vue js/Vuetify 网站。 未受保护的路由工作正常,但是当我尝试向 API 中的受保护路由发送 axios 请求时,我只收到未找到令牌的错误。
我不知道问题出在 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
路由时的错误:
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."
【问题讨论】:
你的问题解决了吗? 【参考方案1】:你有没有尝试添加
RewriteRule .* - [env=HTTP_AUTHORIZATION:%HTTP:Authorization]
到您的 .htaccess 文件?
【讨论】:
以上是关于找不到 Slim jwt 令牌(由 axios 请求发送)的主要内容,如果未能解决你的问题,请参考以下文章
Angularjs 和 slim 框架 JWT 身份验证和令牌刷新流程