Skip to content

Instantly share code, notes, and snippets.

@tuupola
Last active March 4, 2019 09:47
Show Gist options
  • Save tuupola/bb90a2311576e2f1573f8e927c78f86e to your computer and use it in GitHub Desktop.
Save tuupola/bb90a2311576e2f1573f8e927c78f86e 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();
@zio-mitch
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment