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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题