Skip to content

Instantly share code, notes, and snippets.

@diego-mi
Forked from tuupola/index.php
Created July 2, 2017 09:26
Show Gist options
  • Save diego-mi/634a66183153c724403b8df9db36111f to your computer and use it in GitHub Desktop.
Save diego-mi/634a66183153c724403b8df9db36111f 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