我正在建立一个PHP Slim Framework API和tuuopla slim-jwt-auth作为JWT令牌认证中间件的Vue js / Vuetify网站。 不受保护的路由运行正常,但是当我尝试将axios请求发送到API中的受保护路由时,我仅收到未找到令牌的错误。
我不知道问题出在Vue js,axios还是API配置上。 curl
,邮递员在访问受保护的路由时会按预期提供解码后的密钥,只有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);
}
);
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.
{
"status": "error",
"message": "Token not found."
}
答案 0 :(得分:0)
您尝试添加
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
到您的.htaccess文件?