Java – handling 401 errors (spring security)
•
Java
I can handle 404 errors
@ResponseStatus(value = HttpStatus.NOT_FOUND) @ExceptionHandler(NoHandlerFoundException.class) @ResponseBody public void noHandlerFoundException (HttpServletResponse response) throws IOException{ //some code }
But how to deal with 401 errors?
Editing I use Java instead of the web xml
Edit what I should put in nohandlerfoundexception to handle httpstatus UNAUTHORIZED
edit
When validation fails, my method fails validation:
public class StatelessLoginFilter extends AbstractAuthenticationProcessingFilter { protected void unsuccessfulAuthentication(HttpServletRequest request,HttpServletResponse response,AuthenticationException Failed) throws IOException,ServletException { SecurityContextHolder.clearContext(); if (logger.isDebugEnabled()) { logger.debug("Authentication request Failed: " + Failed.toString()); logger.debug("Updated SecurityContextHolder to contain null Authentication"); logger.debug("Delegating to authentication failure handler " + failureHandler); } // response.setCharacterEncoding("UTF-8"); // response.getWriter().write(jsonService.toString(jsonService.getResponse(false,"Не удалось авторизоваться","401"))); rememberMeServices.loginFail(request,response); failureHandler.onAuthenticationFailure(request,response,Failed); } }
This code sends 401 error HTML I need to send JSON, you can see it in the comments
Solution
This is a complete handler for all a small number of error pages:
@Controller public class ErrorCodeController extends BaseController { @ExceptionHandler(ApplicationException.class) @RequestMapping(value="errorPage400",method=RequestMethod.GET) @ResponseStatus(value = HttpStatus.BAD_REQUEST) public String handleBadRequest(ApplicationException ex,ModelMap map) { map.addAttribute("http-error-code",HttpStatus.BAD_REQUEST); return processErrorCodes(ex,map); } @ExceptionHandler(ApplicationException.class) @RequestMapping(value="errorPage401",method=RequestMethod.GET) @ResponseStatus(value=HttpStatus.UNAUTHORIZED,reason="Unauthorized Request") public String handleUnauthorizedRequest(ApplicationException ex,HttpStatus.UNAUTHORIZED); return processErrorCodes(ex,map); } @ExceptionHandler(ApplicationException.class) @RequestMapping(value="errorPage404",method=RequestMethod.GET) @ResponseStatus(HttpStatus.NOT_FOUND) public String handleNotFoundRequest(ApplicationException ex,HttpStatus.NOT_FOUND); return processErrorCodes(ex,map); } @ExceptionHandler(ApplicationException.class) @RequestMapping(value="errorPage500",method=RequestMethod.GET) @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR,reason="Internal Server Error") public String handleInternalServerError(ApplicationException ex,HttpStatus.INTERNAL_SERVER_ERROR); return processErrorCodes(ex,map); } @ExceptionHandler(ApplicationException.class) public void handleApplicationExceptions(Throwable exception,HttpServletResponse response) { } private String processErrorCodes(ApplicationException ex,ModelMap map){ map.addAttribute("class",ClassUtils.getShortName(ex.getClass())); map.addAttribute("message",ex.getMessage()); map.addAttribute("errorMessage",ex.getErrorMessage()); map.addAttribute("errorCode",ex.getErrorCode()); map.addAttribute("timestamp",ex.getCurrentDate()); return "errorPage"; } }
Basic controller:
@Controller @RequestMapping("/") public class BaseController { // Remember to add any exception that you SUSPECT can be thrown in this web application. @ExceptionHandler({ApplicationException.class,NullPointerException.class}) public ModelAndView handleException(Throwable exception,HttpServletRequest req) { ModelMap model = new ModelMap(); ApplicationException ex = new ApplicationException(); String timeStamp = ex.getCurrentDate().toString(); //String temp = ClassUtils.getShortName(ex.getClass()); //model.addAttribute("class",ClassUtils.getShortName(ex.getClass())); model.addAttribute("timeStamp",timeStamp); return new ModelAndView("errorPage",model); }
Web. xml:
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>myApp</display-name> <error-page> <error-code>400</error-code> <location>/errorPage400.xhtml</location> </error-page> <error-page> <error-code>401</error-code> <location>/errorPage401.xhtml</location> </error-page> <error-page> <error-code>404</error-code> <location>/errorPage404.xhtml</location> </error-page> <error-page> <error-code>500</error-code> <location>/errorPage500.xhtml</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/errorPage.xhtml</location> </error-page>
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码