Reputation: 385
It's my first using slim 3 framework skeleton project, they say
There is also a skeleton project which will give you a quick-start for a sample application, so use that if you’d rather just have something working rather than exploring how all the moving parts work.
In real life it so hard to integrate JSON Web Token Authentication Middleware
I try to following step by step in tutorial but still not working. Please help me ?
this is my code
middleware.php
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => "/",
"passthrough" => "/test",
"secret" => "thisissecret"
]));
and my / route
routes.php
$app->get('/',App\MemberController::class);
but the result is like this image below, 401: Unauthorized
Upvotes: 3
Views: 3177
Reputation: 33
if you are using apache server and serve over https protocol then your .htaccess file looks like
RewriteEngine On
RewriteCond %{HTTPS} On
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]
# Set the headers for the restful api
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Accept, Origin, Authorization"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT, PATCH"
Upvotes: 0
Reputation: 8065
Using firebase/php-jwt
$payload = [
"sub" => "[email protected]"
];
$token = JWT::encode($payload,'JWT-secret-key');
If using Apache add the following to the .htaccess file. Otherwise PHP wont have access to Authorization: Bearer header
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => "/api",
"passthrough" => ["/test"],
"secret" => "JWT-secret-key",
"secure" => false,
"callback" => function ($request, $response, $arguments) use ($container) {
$container["jwt"] = $arguments["decoded"];
},
"error" => function ($request, $response, $arguments) {
$data["status"] = "0";
$data["message"] = $arguments["message"];
$data["data"] = "";
return $response
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
]));
Upvotes: 2
Reputation: 20377
You are misunderstanding the parameter secret
. It is not the the token. It is the secret key you use to sign the token.
It is up to you how you generate the token. There is for example an online tool. You can also generate token with PHP.
use Firebase\JWT\JWT;
$payload = [
"sub" => "[email protected]"
];
$token = JWT::encode($payload, "thisissecret", "HS256");
Before using JWT is is good idea to read this introduction.
Upvotes: 2