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

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

问题描述

是否可以使用 spring-security 插件在 grails3 应用程序中配置 CSRF 保护,除了 grails 表单的 useToken 属性外,我找不到任何东西,然后在控制器内部调用 withForm.但这实际上不是一个非常灵活的解决方案.我喜欢像 here

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.您需要在 grails resouces.groovy 中定义新 bean(参见下面的 snipet - csrfFilter bean).您可以定义自己的accessDeniedHandlerrequireCsrfProtectionMatcher.这是来自 resources.groovy 的片段:

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 令牌:

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天全站免登陆