在codeigniter中提交自定义表单后,如何检查CSRF令牌是否有效

问题描述 投票:1回答:1

我正在使用CodeIgniter自定义表单,在此表单中,我在表单提交后使用了CSRF令牌我想在表单提交后检查控制器,如果CSRF令牌有效,请问有谁可以帮我解决这个问题?

PHP表单代码

<form role="form" data-parsley-validate="" novalidate="" class="mb-lg" action="?c=
    <?php echo isset($controller) ? $controller : "welcome"; ?>&m=login" method="post">
    <div class="form-group has-feedback">
        <input name="email" id="exampleInputEmail1" type="email" placeholder="Enter email" autocomplete="off" required class="form-control">
        <span class="fa fa-envelope form-control-feedback text-muted"></span>
    </div>
    <div class="form-group has-feedback">
        <input name="password" id="exampleInputPassword1" type="password" placeholder="Password" required class="form-control">
        <span class="fa fa-lock form-control-feedback text-muted"></span>
    </div>
    <div class="clearfix">
        <div class="pull-right">
            <a href="?c=<?php echo isset($controller) ? $controller : "welcome"; ?>&m=resetpassword" class="text-muted">Forgot your password?</a>
        </div>
    </div>
    <?php 
    $csrf = array(
        'name' => $this->security->get_csrf_token_name(),
        'hash' => $this->security->get_csrf_hash()
    );
    ?>
    <input type="hidden" name="<?php echo $csrf['name'];?>" value="<?php echo $csrf['hash'];?>" />
    <button type="submit" class="btn btn-block btn-primary mt-lg">Login</button>
</form>
codeigniter
1个回答
1
投票

CodeIgniter会自动为您完成此操作。如果它无效,它将与show_errorshow_error('The action you have requested is not allowed.', 403);

相关函数可以在/system/core/security类中找到,函数:csrf_verify()csrf_show_error()(如果无效)。


如果您现在已经理解,如果您在配置中启用了csrf并且您没有相应的csrf隐藏字段或使用form_open(为您添加字段),那么当您发布请求时,它将失败并显示上述消息。对于AJAX请求也是如此 - 为ajax请求自动执行此操作,只要有ajax请求,您就可以将其添加到页面顶部:

<script type="text/javascript">
        token["<?php echo $this->security->get_csrf_token_name(); ?>"] = "<?php echo $this->security->get_csrf_hash(); ?>";
        jQuery.ajaxSetup({data: token, type: "POST"});
</script>
© www.soinside.com 2019 - 2024. All rights reserved.