oauth2.0 移动的应用程序:PHP中忽略cookie?

tct7dpnv  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(84)

我的场景如下:我的移动的应用程序向外部网站发送请求,请求授权接收授权代码,该代码被发送到重定向URI以交换“访问令牌”。我想将此令牌存储在firebase实时数据库中,但要使用通过我的应用程序发出请求的用户的唯一用户ID。原因,可能有多个用户向网站发出该请求,当然我需要将它们分开,包括令牌的安全存储。没有uuid,一切都正常,令牌保存到firebase。
我现在已经开始更新我的代码。使用OAuth 2.0,但是,第三方wesbite上没有设置状态管理,所以我不能只传递编码的uuid,因为服务器只返回授权码。所以我写了一个脚本(storeUuid. php),它接收编码的uuid,解码它,保存在一个定时cookie中,以便同一个域(www.example.com)上的其他脚本auth.example.com可以访问cookie并使用它。在服务器上有第二个脚本(redirect.php),它由对第三方网站的授权请求触发,接收授权代码并应该将其交换为访问令牌。然而,在此之前,它应该访问cookie并提取uuid。然而,它总是抛出{error:UUID not found in the cookie}。

<?php
// storeUuid.php
session_start();
// Function to return JSON response
function jsonResponse($data) {
    header('Content-Type: application/json');
    echo json_encode($data);
}

// Function to log errors
function logError($message) {
    error_log("Error: $message");
}

session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/', 
    'domain' => 'auth.example.com', 
    'secure' => true,
    'httponly' => true,
    'samesite' => 'None' 
  ]);

// Function to store UUID in session and cookie
function storeUUID($encodedUUID) {
    $decodedUUID = base64_decode($encodedUUID);
    
    if ($decodedUUID) {
        $_SESSION['userUid'] = $decodedUUID;
        setcookie("decodedUUID", $decodedUUID, time()+3600, "/", "auth.example.com"); 
        jsonResponse(["success" => "UUID stored in session and cookie.", "decodedUUID" => htmlspecialchars($decodedUUID), "sessionId" => session_id(), "cookie" => ($_COOKIE)]);
    } else {
        logError("No UUID provided or decoding failed.");
        jsonResponse(["error" => "No UUID provided or decoding failed.", "sessionId" => session_id()]);
    }
}

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $encodedUUID = isset($data['encodedUserUid']) ? $data['encodedUserUid'] : null;

    if ($encodedUUID) {
        storeUUID($encodedUUID);
    } else {
        logError("No encoded UUID provided in POST request.");
        jsonResponse(["error" => "No encoded UUID provided in POST request.", "sessionId" => session_id()]);
    }
} else {
    logError("Invalid request method.");
    jsonResponse(["error" => "Invalid request method.", "sessionId" => session_id()]);
}
?>

个字符
这是两个文件。如上所述,我从storeUuid.php获得的响应日志显示了我所能告诉的一切工作:

LOG  Initiating OAuth process...
 LOG  Encoded user UID: ABCD1234
 LOG  Response from storeUuid.php: Array
(
    [decodedUUID] => BFM6OIHuCBe56s08cgcnmiEotff1
    [PHPSESSID] => lgh2gphfbbolcimv0abkkmrere
)
{"success":"UUID stored in session and cookie.","decodedUUID":"5678DCBA","sessionId":"my_session_id","cookie":{"decodedUUID":"5678DCBA","PHPSESSID":"my_session_id"}}
 LOG  Authorization URL: https://auth.3rdparty.com/oauth/authorize?response_type=code&client_id=(MY_CLIENT_ID)&redirect_uri=https://auth.example.com/redirect&scope=read
 LOG  OAuth URL opened successfully.


但是我正在测试的应用程序设备上的浏览器正在抛出错误,它无法在cookie或会话中找到UUID。
我在redirect.php中添加了print_r($_COOKIE);来查看cookie的内容,但是什么都没有显示。
任何建议将是非常有帮助的!

mbzjlibv

mbzjlibv1#

我通过使用定制的会话处理程序找到了一个解决方案。

class CustomSessionHandler implements SessionHandlerInterface {
    private $redis;

    public function open($savePath, $sessionName) {
        // Initialize the Redis connection
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
        return true;
    }

    public function close() {
        // Close the Redis connection
        $this->redis->close();
        return true;
    }

    public function write($id, $data) {
        $this->setSessionData($id, $data);
        return true;
    }

    public function read($id) {
        $data = $this->redis->hGet("session:$id", "data");
        return $data === false ? '' : $data;
    }    

    public function destroy($id) {
        // Attempt to delete the session data from Redis
        $result = $this->redis->del("session:$id");
        
        if ($result === false) {
            // Log the error or handle it accordingly
            error_log("Failed to delete session data for ID: $id");
            return false;
        }
        
        return true;
    }     

    public function gc($maxlifetime) {
        // Redis automatically handles expiration, so no need for manual garbage collection
        return 0;
    }

    public function setSessionData($id, $data) {
        // Set session data in your custom way
        $this->redis->hSet("session:$id", "data", $data);
        $this->redis->expire("session:$id", 600); // data expires after 10 minutes
    }

    public function getSessionData($id) {
        // Retrieve session data from Redis based on the session ID
        return $this->redis->hGet("session:$id", "data");
    }
}

// Register the custom session handler and start session
$handler = new CustomSessionHandler();
session_set_save_handler($handler, true);
session_start();

字符串

相关问题