使用 jwt 令牌时如何检测用户(Slim-jwt-auth)

How to detect the user when using a jwt token (Slim-jwt-auth)

我目前正在使用带有 slim-jwt-auth 的 Slim。

我的项目基于 slim-api-骨架 (https://github.com/tuupola/slim-api-skeleton)。 我只需要为创建令牌的用户允许路由。

我用下面的代码完成了:

        //check if it is the right user
        $user = \User::find($args["uid"]);

        $token = $request->getHeader('HTTP_AUTHORIZATION');                
        $token = str_replace("Bearer ", "", $token);
        $secret = getenv("JWT_SECRET");
        $decoded = JWT::decode($token[0], $secret, array("HS256"));

        if ($decoded->sub != $user->email) 
        {
            throw new ForbiddenException("User not allowed to read.");
        }

是否正确?或者有更好的方法吗?

这是一种方法。虽然我不会手动解析令牌。默认情况下,JWT 的解析值存储在 $request->token 属性中。使用它,您可以将代码缩短为以下内容。

$app->get("/user/{uid}", function ($request, $response, $arguments) {
    $user = \User::find($arguments["uid"]);

    $token = $request->getAttribute("token");

    if ($token->sub !== $user->email) ) {
        throw new ForbiddenException("User not allowed to read.");
    }
});

您可以使用 attribute 设置更改此行为。