dousilie9522
2016-07-07 03:25
浏览 30
已采纳

在与安全表单相同的页面中生成CSRF令牌是否安全?

I currently have these 2 functions, one for generating token and one for checking the validity:

function getToken() {
    if(isset($_SESSION['token'])) {
        return $_SESSION['token']; 
    } else {
        $token = //random key generator goes here;
        $_SESSION['token'] = $token;
        return $token;
    }
}

function validateToken($token) {
    if ($token == getToken()){
        return true;
    } else {
        return false;
    }
}

And my registration form includes this hidden input:

<input type="hidden" name="token" value="<?php echo getToken(); ?>">

Is this safe? I'm asking because what if session of legit user expires and then they get CSRF'd to this register form and token gets generated by the malicious site/iframe itself because one didn't already exist in the session, therefore authenticating just fine?

Assume that user stays logged in because of cookies.

Am I understanding things wrongly here? Can't remote linking like iframes generate sessions in your backend?

图片转代码服务由CSDN问答提供 功能建议

我目前有这两个函数,一个用于生成令牌,另一个用于检查有效性: function getToken(){ if(isset($ _ SESSION ['token'])){ return $ _SESSION ['token']; } else { $ token = //随机密钥生成器到此处; $ _SESSION ['token'] = $ token; 返回$ token; } } 函数validateToken($ token){ if($ token == getToken()){ return true; } else { return false; } } \ n

我的注册表包含这个隐藏的输入:

 &lt; input type =“hidden”name =“token”value =“&lt;?php echo getToken(  );?&gt;“&gt; 
   
 
 

这样安全吗? 我问,因为如果合法用户的会话到期然后他们获得CSRF到这个注册表单并且令牌由恶意网站/ iframe本身生成,因为会话中尚未存在,因此认证很好?

假设用户因cookie而一直保持登录状态。

我在这里是否理解错误? 像iframe这样的远程链接不能在后端生成会话吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqv84329 2016-07-07 04:21
    已采纳

    No. As far as I can tell, you are doing it right way as the token should be generated as soon as the user comes to the form page. Then you will generate it to know for sure that someone (real user) actually has visited your form and then you are setting the token for them.

    When they do any action with the form, you are checking with the token to see if the token is valid for that user. So, I guess you are doing it right.

    One thing, generate the token and store it on session when an user requests/comes to the form page. It would be better if you generate it every time a request comes. Then after each successful form submission, clear the checked token from session.

    打赏 评论

相关推荐 更多相似问题