package edu.travel.warehouse.config; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class MyAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException e) throws IOException, ServletException { resp.setContentType("application/json;charset=UTF-8"); Map map = new HashMap(); map.put("code", "450"); map.put("message", e.getMessage()); map.put("path", req.getServletPath()); map.put("timestamp", String.valueOf(System.currentTimeMillis())); resp.setContentType("application/json"); resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(resp.getOutputStream(), map); } catch (Exception ex) { throw new ServletException(); } } }