首页 > 解决方案 > 标头未全局发送

问题描述

$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 语句,这意味着当用户登录时我无法解码 jwt。如何修复授权标头以发送到其他功能?谢谢你

标签: phpheaderslim

解决方案


推荐阅读