【问题标题】:How to write accessDeniedHandler in grails如何在grails中编写accessDeniedHandler
【发布时间】:2018-06-26 17:28:11
【问题描述】:

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

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

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

【问题讨论】:

  • 只是指出您不必提供它们,您可以使用默认值

标签: grails groovy spring-security csrf-protection


【解决方案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");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多