且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Slim框架JWT中间件问题

更新时间:2023-11-17 08:10:28

那么不要检查当前路由的令牌是否是实际的登录路由。

要获取中间件内的路由,您需要首先配置slim来确定路由中间件被执行:

 使用Slim \App; 

$ app = new App([
'settings'=> [
'determineRouteBeforeAppMiddleware'=> true
]
])$ b然后你可以通过 $ route = $ request-> getAttribute来访问当前的路由('route'); 中间件:

您现在可以检查当前路由是否为登录路由

  $ app-> add(function(Request $ request,Response $ response,callable $ next){
$ route = $ request- > getAttribute('route');
$ name = $ route-> getName();
$ b $ if($ name!=='login'){
/ / do authentication
}

return $ next($ request,$ response);
});

注意:您需要使用 - >来设置路由的名称。 setName($ name)就像这样:

  $ app-> get / login',函数($ request,$ response,$ args){
//做某事
}) - > setName('login');


I'm having a problem with my slim app, I'm trying to use JsonWebToken for authentication but I don't know how to do it the right way.

My middleware is blocking all the requests that dont include a valid token, but what about the first authentication post request that obviously don't include a valid token. Here's my code if it helps (in middleware file):

$app->add(function (Request $request,Response $response, $next) use ($app){
    $stringToken = $request->getHeader("Authorization")[0];
    if($stringToken == NULL) {
        return $response->withJson(array("Connection"=>"Fail On Token", "Error"=>"No token Provided."));
    } else {
        $jsonObjectToken = json_decode($stringToken);
        try{
            JWT::decode($jsonObjectToken->jwt, JWTController::$secretKey, array('HS512'));
        }catch (Exception $e){
            return $response->withJson(array("Connection"=>"Fail On Token", "Error"=>$e->getMessage()));
        }
        $response = $next($request, $response);

        return $response;
    }
});

You can check which route is called inside the middleware and then do not check the token of the current route is the actual login route.

For getting the route inside the middleware you need first to configure slim to determinate the route before the middleware gets executed:

use Slim\App;

$app = new App([
    'settings' => [
        'determineRouteBeforeAppMiddleware' => true
    ]
])

Then you can access the current route with $route = $request->getAttribute('route'); inside the middleware:

You now can check if the current route is the login route

$app->add(function (Request $request, Response $response, callable $next) {
    $route = $request->getAttribute('route');
    $name = $route->getName();

    if($name !== 'login') {
        // do authentication
    } 

    return $next($request, $response);
});

Note: You need to set the name of the Route with ->setName($name) on the route like so:

$app->get('/login', function ($request, $response, $args) {
    // do something
})->setName('login');