Java tutorial
package com.miserablemind.butter.security; import com.miserablemind.butter.domain.model.user.user.AppUser; import org.apache.log4j.Logger; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /* * Miserable Mind * http://www.butter.miserablemind.com * The MIT License (MIT) */ /** * Handle {@link AccessDeniedException}. It logs the exception and redirects to 500 error page. * Specifically 500, because explicitly exposing user restrictions could raise security issues. * * @author <a href="http://www.miserablemind.com" target="_blank">miserablemind</a> */ @Component public class MyAccessDeniedHandler implements AccessDeniedHandler { private static final Logger logger = Logger.getLogger(MyAccessDeniedHandler.class); /** * Handle Exception Method * * @param request {@link HttpServletRequest} provides session and {@link SecurityContext} * @param response used for redirecting to 500 page * @param accessDeniedException exception used for logging the stack trace * @throws IOException * @throws ServletException */ @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { long userId = 0; SecurityContext securityContext = (SecurityContext) request.getSession() .getAttribute("SPRING_SECURITY_CONTEXT"); if (securityContext != null) { Object principal = securityContext.getAuthentication().getPrincipal(); if (principal != null && principal != "anonymousUser") { AppUser user = (AppUser) principal; userId = user.getId(); } } logger.error("Accessing Denied. User ID: " + userId + " URL: " + request.getServletPath(), accessDeniedException); response.sendRedirect("/error/500"); } }