Spring Security — Configuring 403 / Custom Access Denied Page
1 min readFeb 13, 2020
In this post I will try to demonstrate how we can customize our default 403 / access denied page.
To understand how to work with Spring Security, you can read this post.
- Configuration
We can achieve this in 2 ways.
- Calling
accessDeniedPage(String s)
and passing a controller mapping in it. - Writing our own CustomAccessDeniedHandler class.
Below I have demonstrated the both options.
Option 1:
http
.exceptionHandling()
.accessDeniedPage("/403");
Option 2:
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/403");
}
}
Now we need to use it in our WebSecurityConfiguration class.
http
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler());
- We need to create a controller with mapping /403 and a .jsp page
i. /403 mapped controller
@GetMapping("/403")
public String _403() {
return "403";
}
ii. JSP page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>403</title>
</head>
<body>
<h1>Sorry, You don't have sufficient permission to visit this page.</h1>
</body>
</html>
The source code for this tutorial can be found here.