How to write accessDeniedHandler in grails

霸气de小男生 提交于 2019-12-10 19:14:23

问题


I am new to groovy, I have implemented CSRF Token in grails in following manner. CSRF filter is added in resource.groovy

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

But i don't know how to initialize fnAccessDeniedHandler and fnRequireCsrfProtectionMatcher . Thanks in advance.


回答1:


The value in ref has to be a bean(https://docs.grails.org/latest/guide/spring.html). If you want to override accessDeniedHandler and requireCsrfProtectionMatcher, You would need to create custom classes, and create beans in resources.groovy. As an example, to create bean fnAccessDeniedHandler, you would do something like this.

Add the following in resources.groovy

fnAccessDeniedHandler(CustomAccessDeniedHandler)

And create a class CustomAccessDeniedHandler which implements AccessDeniedHandler.

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");
    }
}


来源:https://stackoverflow.com/questions/48307781/how-to-write-accessdeniedhandler-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!