Skip to content

Instantly share code, notes, and snippets.

@vasildakov-zz
Forked from tuupola/index.php
Created February 5, 2017 18:54
Show Gist options
  • Save vasildakov-zz/57756378da8f816ea35d71eb97ecc0e7 to your computer and use it in GitHub Desktop.
Save vasildakov-zz/57756378da8f816ea35d71eb97ecc0e7 to your computer and use it in GitHub Desktop.
Use JWT Authentication middleware with ZF Expressive
<?php
use Zend\Expressive\AppFactory;
use Firebase\JWT\JWT;
use Slim\Middleware\JwtAuthentication;
chdir(dirname(__DIR__));
require "vendor/autoload.php";
$app = AppFactory::create();
$app->get("/", function ($request, $response, $next) {
$response->getBody()->write("Hello, world!");
return $response;
});
$app->get("/ping", function ($request, $response, $next) {
$response->getBody()->write("pong");
return $response;
});
$app->get("/api", function ($request, $response, $next) {
$response->getBody()->write("api");
return $response;
});
$app->post("/token", function ($request, $response, $arguments) {
$now = new DateTime();
$future = new DateTime("now +2 hours");
$server = $request->getServerParams();
$jti = "LAKSJLASJDALSDJ";
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp(),
"jti" => $jti
];
$secret = "supersecretkeyyoushouldnotcommittogithub";
$token = JWT::encode($payload, $secret, "HS256");
$data["status"] = "ok";
$data["token"] = $token;
return $response->withStatus(201)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
$app->pipe(new JwtAuthentication([
"secret" => "supersecretkeyyoushouldnotcommittogithub",
"path" => ["/"],
"passthrough" => ["/token", "/ping"],
"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->pipeRoutingMiddleware();
$app->pipeDispatchMiddleware();
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment