简体   繁体   English

如何处理Slim API JWT身份验证

[英]How to handle Slim API JWT Authentication

I already generated a token from my api login using this code: 我已经使用以下代码从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);
    }

So I have a token now, how can I use the token to other api? 所以我现在有一个令牌,如何将令牌用于其他api? What I mean is, i dont want anybody to perform this api without logging in. 我的意思是,我不希望任何人都无需登录即可执行此api。

This is my sample API method: 这是我的示例API方法:

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

This is the library i used: https://github.com/firebase/php-jwt 这是我使用的库: https : //github.com/firebase/php-jwt

Thank you very much for your help. 非常感谢您的帮助。

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 您只需要为您的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);
                }
    }
    });
    `

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

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