Reputation: 511
I am using Slim Framework to develop a REST API with JSON Web Token and then test it with Postman. I have created the Database connection, I have tested GET, POST, PUT, DELETE in Postman, everything works fine and now I come to the JWT Authentication. Bear in mind that Basic Http Authentication works fine also. So, code
.htaccess
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
customers.php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
$container = $app->getContainer();
$container["jwt"] = function ($container) {
return new StdClass;
};
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => "/api",
"passthrough" => ["/api/token", "/admin/ping"],
"secure" => true,
"environment" => "HTTP_X_TOKEN",
"header" => "X-Token",
"secret" => "supersecretkeyyoushouldnotcommittogithub",
"callback" => function ($request, $response, $arguments) use ($container) {
$container["jwt"] = $arguments["decoded"];
},
"error" => function ($request, $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));
}
]));
$app->add(function($request, $response, $next) {
$token = $request->getQueryParams()["token"];
if (false === empty($token)) {
$request = $request->withHeader("Authorization", "Bearer {$token}");
}
return $next($request, $response);
});
//Get All Customers
$app->get('/api/customers', function(Request $request, Response $response){
$sql = "SELECT * FROM customers";
try{
//Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$customers = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($customers);
$fp = fopen('empdata3.json', 'w');
fwrite($fp, json_encode($customers));
fclose($fp);
header("Location: https://www.pawebgate.com/slimapp3/public/empdata3.json");
die();
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
//Get Specific Customer
$app->get('/api/customer/{id}', function(Request $request, Response $response){
$id = $request->getAttribute('id');
$sql = "SELECT * FROM customers where id = $id";
try{
//Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$customer = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($customer);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
Can you please help me on how to set Postman in order to test the above functionality, or any other steps I have to do in order to achieve JWT Auth? I always get "Token not found in Postman" Thanks
Upvotes: 0
Views: 3989
Reputation: 687
First, you need to create a route for get the Token, like this:
$app->post('/auth/token', function(Request $request, Response $response, array $args) {
$data = $request->getParsedBody();
$email = $data['email'] ?? null;
$password = $data['password'] ?? null;
/*[select logic here]*/
$user = $db->query("SELECT * FROM customers WHERE email = $email AND password = $password")...
/*[select logic here]*/
if($user){
$key = 'supersecretkeyyoushouldnotcommittogithub';
return $response->withJson([
'token' => JWT::encode($user, $key)
]);
}
return $response->withJson(['status' => 'error'], 401);
});
Then, you can copy the response and make a POST request in Postman, adding the token to a header "Authorization".
Upvotes: -1