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?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!