标头未全局发送

时间:2019-03-26 13:05:06

标签: php header slim

$app->group('/api', function(\Slim\App $app) {

  $app->post('/login', function (Request $request, Response $response, array $args) {

    $key = "supersecretkeyyoushouldnotcommittogithub";

    $input = $request->getParsedBody();
    $settings = $this->get('settings'); // get settings array.
    $sql = "SELECT id, password FROM users WHERE id= :id";
    $sth = $this->db->prepare($sql);
    $sth->bindParam("id", $input['id']);
    $sth->execute();
    $user = $sth->fetchObject();

    // verify user id 
    if(!$user) {
        return $this->response->withJson(['error' => true, 'message' => 'NO ID '], 404)->withHeader('Content-type', 'application/json;charset=utf-8', 404);
    }
    // Compare the input password and the password from database for a validation
    if (strcmp($input['password'],$user->password)) {
        return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.'], 404)->withHeader('Content-type', 'application/json;charset=utf-8', 404);  
    }

    $payload = array(
        "iat" => time(),
        "exp" => time() + 36000,
        // "id" => $input['id']
        "context" => [
            "user" => [
                "id" => $input['id']
            ]
        ]
    );

    try {
        $token = JWT::encode($payload, $settings['jwt']['secret'], "HS256"); // $token store the token of the user
    } catch (\Exception $e) {
        echo json_encode($e);
    }

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


    return $this->response->withJson($decoded)
                          ->withHeader('Content-type', 'application/json', 200)
                          ->withHeader('Authorization', $token);


    // return $this->response->withJson(['token' => $token]);

     print_r($decoded);


});

$app->get('/get', function (Request $request, Response $response, array $args) {

    if ($request->getHeader('Authorization')) {
        print_r ($request);
    } else  {
        print_r ('FAILED');
    }

});

});

这里我有我的代码,在/ api / login中它可以解码jwt,但是在/ api / get内部时,它无法检测到我的授权标头并返回FAILED / else语句,这意味着当用户登录。如何修复授权标头以发送到其他功能?谢谢

0 个答案:

没有答案