【问题标题】:How to detect the user when using a jwt token (Slim-jwt-auth)使用 jwt 令牌时如何检测用户 (Slim-jwt-auth)
【发布时间】:2017-01-06 22:42:49
【问题描述】:

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

我的项目基于 slim-api-skeleton (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.");
        }

正确吗?还是有更好的方法?

【问题讨论】:

    标签: authentication jwt slim


    【解决方案1】:

    这是一种方法。虽然我不会手动解析令牌。默认情况下,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 设置更改此行为。

    【讨论】:

    • 谢谢...它有效。我刚刚更改了获取令牌的方式,因为直接使用 $request->token->sub 对我不起作用。所以,我使用了以下方式: $token = $request->getAttribute("token"); if ($token->sub !== $user->email) ...
    猜你喜欢
    • 2017-04-06
    • 1970-01-01
    • 2016-07-18
    • 2020-04-19
    • 2022-07-19
    • 2018-08-14
    • 1970-01-01
    • 2015-06-28
    • 2018-08-01
    相关资源
    最近更新 更多