【问题标题】:How to handle Slim API JWT Authentication如何处理 Slim API JWT 身份验证
【发布时间】:2017-05-29 21:08:27
【问题描述】:

我已经使用此代码从我的 api 登录生成了一个令牌:

    if ($isCorrect == 1) {
        $key = "example_key";
        $token = array(
            "iss" => "http://mywebsite.com",
            "iat" => 1356999524,
            "nbf" => 1357000000,
            'data' => [                  
                'userName' => $UserName,
            ]
        );

        $jwt = JWT::encode($token, $key);
        $decoded = JWT::decode($jwt, $key, array('HS256'));

        $unencodedArray = ['jwt' => $jwt];
        echo json_encode($unencodedArray);
    }

所以我现在有一个令牌,我怎样才能将令牌用于其他 api?我的意思是,我不希望任何人在不登录的情况下执行此 API。

这是我的示例 API 方法:

$app->get('/api/user/{UserId}', function($request){ 
//Select query here
});

这是我使用的库:https://github.com/firebase/php-jwt

非常感谢您的帮助。

【问题讨论】:

  • "我不希望任何人在不登录的情况下执行此 api。"我不明白你的意思。获取 JWT 是通过登录过程。您是否尝试使用多个身份验证层?或者询问如何验证用户是他们所说的身份,从而可以安全地获得识别他们的 JWT(这个问题会非常广泛)?
  • 我的意思是我的 API 可以被任何人访问,所以如果我有一个删除方法,任何人都可以在不登录/生成 JWT 的情况下执行此操作。
  • 你可以使用JWT认证中间件:github.com/tuupola/slim-jwt-auth
  • 非常感谢先生。它有效。

标签: php jwt slim


【解决方案1】:

您只需要为您的 API 添加一个中间件方法 这将使用该用户名检查 JWT 令牌的验证 然后将请求传递给 API

`

 $app->add( function ( $Req ,$Res ,$next ){
       //get token,username from the user 
    $token= $Req->getParsedBodyParam('token');
    $user_name=$Req->getParsedBodyParam('username');
    //check for empty of any of them
    if(empty ($token)|| empty($user_name)  ){
    $message=array("success"=>false,'message'=>'Some data is empty');
    return $Res->withStatus(401)
               -> withJson($message);
    }
    else{ 

    //Validation test for the taken for this user name 
                $decoded_token = $this->JWT::decode($token, 'YourSecret key', array('HS256'));
                if( isset($decoded_token->data->userName) && $decoded_token->data->userName == $user_Name ){
               $message=array('message'=>'the token is valid');
//pass through the next API 
                 $Res=$next($Req,$Res->withJson($message));
               return $Res;
                }
                else{
    $message=array("sccess"=>false,"message"=>"Token Validation Error",'code'=>201);
    return $Res->withStatus(401)
            ->withJson($message);
                }
    }
    });
    `

【讨论】:

    猜你喜欢
    • 2017-05-18
    • 2020-09-19
    • 2014-07-24
    • 2018-10-21
    • 1970-01-01
    • 2016-04-24
    • 2017-07-30
    • 2016-03-24
    • 2019-02-14
    相关资源
    最近更新 更多