简体   繁体   English

Slim框架JWT中间件问题

[英]Slim framework JWT middleware Issue

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. 我的瘦身应用程序遇到问题,我正在尝试使用JsonWebToken进行身份验证,但是我不知道如何正确地进行操作。

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: 为了使路由进入中间件内部,您需要先配置slim以在执行中间件之前确定路由:

use Slim\App;

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

Then you can access the current route with $route = $request->getAttribute('route'); 然后,您可以使用$route = $request->getAttribute('route');访问当前路由$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: 注意:您需要在路由上使用->setName($name)设置路由->setName($name) ,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM