douxi8759 2017-01-14 16:50
浏览 57

如何处理Slim API JWT身份验证

I already generated a token from my api login using this code:

    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);
    }

So I have a token now, how can I use the token to other api? What I mean is, i dont want anybody to perform this api without logging in.

This is my sample API method:

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

This is the library i used: https://github.com/firebase/php-jwt

Thank you very much for your help.

  • 写回答

1条回答 默认 最新

  • doufei4923 2017-04-12 16:44
    关注

    You Just need to add a middleware method for your API that will check the validation of the JWT token with that user name Then pass the request to the 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);
                    }
        }
        });
        `
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog