如何在grails中编写accessDeniedHandler

时间:2018-01-17 18:32:19

标签: grails groovy spring-security csrf-protection

我是groovy的新手,我已经以下列方式在grails中实现了CSRF令牌。 CSRF过滤器添加在resource.groovy

<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
          <assemblyIdentity name="Ninject" publicKeyToken="c7192dc5380945e7" culture="neutral" />
        <bindingRedirect oldVersion="3.3.3.0" newVersion="3.3.4.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

但我不知道如何初始化fnAccessDeniedHandler和fnRequireCsrfProtectionMatcher。 提前致谢。

1 个答案:

答案 0 :(得分:1)

ref中的值必须是bean(https://docs.grails.org/latest/guide/spring.html)。如果要覆盖accessDeniedHandler和requireCsrfProtectionMatcher,则需要创建自定义类,并在resources.groovy中创建bean。举个例子,要创建bean fnAccessDeniedHandler,你可以这样做。

在resources.groovy

中添加以下内容
fnAccessDeniedHandler(CustomAccessDeniedHandler)

创建一个实现AccessDeniedHandler的类CustomAccessDeniedHandler。

public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    public static final Logger LOG
      = Logger.getLogger(CustomAccessDeniedHandler.class);

    @Override
    public void handle(
      HttpServletRequest request,
      HttpServletResponse response, 
      AccessDeniedException exc) throws IOException, ServletException {

        Authentication auth 
          = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            LOG.warn("User: " + auth.getName() 
              + " attempted to access the protected URL: "
              + request.getRequestURI());
        }

        response.sendRedirect(request.getContextPath() + "/accessDenied");
    }
}