3

我已经阅读了很多关于它的内容,但我仍然没有完全理解它。

我将来可能会使用现有解决方案的库,但我现在想了解和实施我自己的系统。

为了无状态和可扩展,我认为我不能将用户上下文存储在服务器上。

主要问题是概念问题,如果我了解系统,我将成功对其进行编码

我已经测试了在 Internet 上找到的我修改过的代码(法国网站参考: http: //blog.nalis.fr/index.php ?post/2009/09/28/Securisation-stateless-PHP-avec-un-jeton-取消会话-(令牌)-保护-CSRF-en-PHP)。你能告诉我它是正确的还是我不明白?

所以要创建一个令牌,我使用这个函数,它以用户数据为参数

define('SECRET_KEY', "fakesecretkey");

function createToken($data)
{
    /* Create a part of token using secretKey and other stuff */
    $tokenGeneric = SECRET_KEY.$_SERVER["SERVER_NAME"]; // It can be 'stronger' of course

    /* Encoding token */
    $token = hash('sha256', $tokenGeneric.$data);

    return array('token' => $token, 'userData' => $data);
}

因此,用户可以验证自己并接收包含令牌(genericPart + 他的数据,已编码)和 hisData 未编码的数组:

function auth($login, $password)
{
    // we check user. For instance, it's ok, and we get his ID and his role.
    $userID = 1;
    $userRole = "admin";

    // Concatenating data with TIME
    $data = time()."_".$userID."-".$userRole;
    $token = createToken($data);
    echo json_encode($token);
}

然后用户可以向我发送他的令牌 + 他的未编码数据以检查:

define('VALIDITY_TIME', 3600);

function checkToken($receivedToken, $receivedData)
{
    /* Recreate the generic part of token using secretKey and other stuff */
    $tokenGeneric = SECRET_KEY.$_SERVER["SERVER_NAME"];

    // We create a token which should match
    $token = hash('sha256', $tokenGeneric.$receivedData);   

    // We check if token is ok !
    if ($receivedToken != $token)
    {
        echo 'wrong Token !';
        return false;
    }

    list($tokenDate, $userData) = explode("_", $receivedData);
    // here we compare tokenDate with current time using VALIDITY_TIME to check if the token is expired
    // if token expired we return false

    // otherwise it's ok and we return a new token
    return createToken(time()."#".$userData);   
}

$check = checkToken($_GET['token'], $_GET['data']);
if ($check !== false)
    echo json_encode(array("secureData" => "Oo")); // And we add the new token for the next request

我对吗?

很抱歉这条长消息,很抱歉我的英语。

在此先感谢您的帮助!

4

1 回答 1

0

您的代码中的问题是:您的整个系统基于$_GET原始帖子是基于 Cookie 的。您应该将令牌存储在 cookie 中(基于您的原始帖子,而不是使用$_GET 顺便说一句;一些调整:

list($tokenDate, $userData) = array_pad(explode("_", $receivedData));

在下一个代码中,我看不到您如何使用$login,$password

function auth($login, $password)
{
    // we check user. For instance, it's ok, and we get his ID and his role.
    $userID = 1;
        $userRole = "admin";

        // Concatenating data with TIME
        $data = time()."_".$userID."-".$userRole;
        $token = createToken($data);
        echo json_encode($token);
    }
于 2015-09-16T05:52:53.293 回答