Mojolicious模板渲染(十三)
一、跨域请求保护
当我们使用POST提交数据时,防御CSRF攻击,是最基本的要求。我们在form表单中使用Mojolicious::Plugin::TagHelpers模块的”csrf_field”helper,生成一个带有csrf_token字段的input标签(当我们提交post表单数据时,会有一个关键字为crsf_token的param,其值便是标签中的token值)。在后台,我们会调用Mojolicious::Validator::Validation模块中”csrf_protect”方法进行token值的校验:
use Mojolicious::Lite -signatures;
get '/' => {template => 'target'};
post '/' => sub ($c) {
# 检查 CSRF token
my $v = $c->validation;
return $c->render(text => 'Bad CSRF token!', status => 403) if $v->csrf_protect->has_error('csrf_token');
#如果检查失败
#检查成功:
my $city = $v->required('city')->param('city');
$c->render(text => "Low orbit ion cannon pointed at $city!") unless $v->has_error;
} => 'target';
app->start;
__DATA__
@@ target.html.ep
<!DOCTYPE html>
<html>
<body>
%= form_for target => begin
%= csrf_field
#此helper生成一个csrf_token
%= label_for city => 'Which city to point low orbit ion cannon at?'
%= text_field 'city', id => 'city'
%= submit_button
%= end
</body>
</html>
如果使用javascript的ajax方法提交post,我们可以使用Mojolicious::Plugin::DefaultHelpers模块的csrf_token helper直接生成token值,并将其放入ajax方法的request header请求头的X-CSRF-Token关键字中。