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."
}