Grails 3 CSRF保护 [英] Grails 3 CSRF protection

查看:198
本文介绍了Grails 3 CSRF保护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用spring-security插件在grails3应用程序中配置CSRF保护,我找不到除useToken属性以外的其他任何内容,然后在控制器中调用withForm。但这实际上不是一个非常灵活的解决方案。我喜欢这样的过滤器

Is it possible to configure CSRF protection in grails3 app using spring-security plugin, I can't find anything except useToken attribute for grails form and then call withForm inside controller. But this is actually not a very flexible solution. I like approach with filter like here

推荐答案

对于csrf保护,我重用 org.springframework.security.web.csrf.CsrfFilter

For csrf protection I reused org.springframework.security.web.csrf.CsrfFilter. You need to define new bean in grails resouces.groovy (See snipet below - csrfFilter bean). You can define your own accessDeniedHandler and requireCsrfProtectionMatcher. Here is the snippet from resources.groovy:

csrfFilter(CsrfFilter, new HttpSessionCsrfTokenRepository()) {
    accessDeniedHandler = ref('fnAccessDeniedHandler')
    requireCsrfProtectionMatcher = ref('fnRequireCsrfProtectionMatcher')
}

现在在Bootstrap.groovy中,将此过滤器添加到过滤器链中:

Now in Bootstrap.groovy add this filter into filter chain:

 SpringSecurityUtils.clientRegisterFilter('csrfFilter',    SecurityFilterPosition.LAST.order + 10)

现在在您的主布局中,GSP添加以下标记以在每个页面上添加csrf标记: / p>

Now in your main layout GSP add following tags to add csrf token on each page:

<meta name="_csrf" content="${_csrf?.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf?.headerName}"/>

现在,您的应用的每个页面上都会显示csrf标记,您可以将它用于每个ajax请求例子(来自application.js的片段(我使用的是grails 3)):

So now csrf token presented on each page of your app, you can use it for each ajax request for example (snippet from application.js (I'm using grails 3)):

$(function () {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
});

对于每个jquery ajax请求,我们现在都发送csrf令牌。

For each jquery ajax request we are sending csrf token now.

这篇关于Grails 3 CSRF保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆