2,258   CSRF Laravel PHP

Laravel5 的csrf采用自动生成和验证的机制,你只需在前端添加参数即可,方法有

1,通过input

// helper函数
<?php echo csrf_field(); ?>
// 或者
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

2,通过header

// html
<meta name="csrf-token" content="{{ csrf_token() }}">
// js
$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});

2,通过第三方package: LaravelCollective/html,它会自动帮你生成csrf的input

// 此方法会生成一个隐藏的input来保存csrf
{!! Form::open(array('url' => 'foo/bar')) !!}

前端添加参数,后端的VerifyCsrfToken middleware会自动验证csrfToken
官网是这样说的

You do not need to manually verify the CSRF token on POST, PUT, or DELETE requests. The VerifyCsrfToken middleware, which is included in the web middleware group, will automatically verify that the token in the request input matches the token stored in the session.




Leave a Reply

Your email address will not be published. Required fields are marked *