tuupola / slim-jwt-auth

PSR-7 and PSR-15 JWT Authentication Middleware
https://appelsiini.net/projects/slim-jwt-auth
MIT License
821 stars 140 forks source link

How to use Callback in 3.x branch? #207

Closed M-Shahbaz closed 3 years ago

M-Shahbaz commented 3 years ago

How to use Callback feature from 2.x branch in 3.x branch?

Need authentication force to fail.

Callback Callback is called only when authentication succeeds. It receives decoded token in arguments. If callback returns boolean false authentication is forced to be failed.

You can also use callback for storing the value of decoded token for later use.

$app = new \Slim\App();

$container = $app->getContainer();

$container["jwt"] = function ($container) {
    return new StdClass;
};

$app->add(new \Slim\Middleware\JwtAuthentication([
    "secret" => "supersecretkeyyoushouldnotcommittogithub",
    "callback" => function ($request, $response, $arguments) use ($container) {
        $container["jwt"] = $arguments["decoded"];
    }
]));
tuupola commented 3 years ago

You could do something similar by returning a 401 response from the after handler.

use Tuupola\Middleware\JwtAuthentication;
use Tuupola\Http\Factory\ResponseFactory;

$app->add(new JwtAuthentication([
    "secret" => "supersecretkeyyoushouldnotcommittogithub",
    "path" => ["/protected"],
    "after" => function ($response, $arguments) {
        if ($authfails) {
            return (new ResponseFactory)->createResponse(401);
        }
        return $response;
    }
]));
M-Shahbaz commented 3 years ago

Ok, thanks