L
L
Lopus2021-10-07 21:07:45
Spring
Lopus, 2021-10-07 21:07:45

Spring security custom template for 403?

How can I make spring security return a 404 response instead of 403 and render the template file templates/error-404.html ?

I found some options where they suggest redirecting to the /error-access-denied controller, and then return the desired html. But is it some kind of crutch? Really in a spring it is impossible to substitute the check?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2021-10-07
@azerphoenix

Good afternoon.
You can use this snippet. Here you can catch the http error code (statusCode), and then if the value of this variable is 403, then display the desired template.

@Controller
@RequiredArgsConstructor
public class HttpErrorController implements ErrorController {

  @RequestMapping("/error")
  public ModelAndView handleError(HttpServletRequest request) {
    Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
    if (status != null) {
      int statusCode = Integer.valueOf(status.toString());
      // тут при помощи switch case находим код 403 и отдаем нужный шаблон.
    }
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("/frontend/templates/http-errors");
    return modelAndView;
  }

  @SuppressWarnings("deprecation")
  @Override
  public String getErrorPath() {
    return null;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question