Spring boot security protects the websites from unauthorized access. If the web page url is directly accessed from the browser, the 403 Forbidden/Access Denied error message will be shown.. In this article, we’ll see how to configure this 403 Forbidden / Access Denied error page.

If an url is accessed without the right role or permission, the server may submit a 403 Forbidden / Access Denied error message. This error page can be modified to give the user the correct information. The Spring Boot Security Module allows you to redirect the url to the error page if the url is accessed without permission.

This article is a follow-up to the Spring boot Security Step by Step 5 page. I suggest that you first visit this page before beginning this article.

Error Message

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Feb 18 19:54:55 IST 2020
There was an unexpected error (type=Forbidden, status=403).
Forbidden


Step 1 – Add Spring Boot Security Configurations

The configuration of the spring boot security is changed to handle the unauthorized access denied error. Spring boot security allows you to add a redirected url if a 403 Forbidden / Access Denied error occurs. The following lines should be added to the Java security configuration of the spring boot configuration.
.and().exceptionHandling().accessDeniedPage("/accessdenied")

The full spring boot security configuration java file looks like the one below. At the end of the configurations, the access denied page configuration is added.

src/main/java/com/yawintutor/SpringBootSecurityConfiguration.java

package com.yawintutor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
public class SpringBootSecurityConfiguration extends WebSecurityConfigurerAdapter {
	
	@Autowired
	AuthenticationSuccessHandler successHandler;
	
	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
			.withUser("user").password("{noop}password").roles("USER")
			.and()
			.withUser("admin").password("{noop}password").roles("ADMIN");
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http
			.csrf().disable()
			.authorizeRequests()
			.antMatchers("/admin/dashboard").hasAnyRole("ADMIN")
			.antMatchers("/user/dashboard").hasAnyRole("USER")
			.and().formLogin().loginPage("/login")
				.successHandler(successHandler)
			.permitAll()
			.and().logout()
			.and().exceptionHandling().accessDeniedPage("/accessdenied");
	}
}	


Step 2 – Modify Controller for unauthorized access denied error page url

In the controller class, add the error page method. If an unauthorized access denied error occurs, this url will be invoked by the controller to display the error message in the browser. Add a mapping between the url page of the error and the jsp page of the error.

src/main/java/com/yawintutor/TestController.java

package com.yawintutor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping
public class TestController {

	............

	@RequestMapping("/accessdenied")
	public ModelAndView accessdenied() {
		return new ModelAndView("accessdenied");
	}

	............
}


Step 3 – Add Unauthorized Access Denied Error JSP Page

Build a jsp file in your jsp folder. This jsp file will be shown if there is an error of 403. If the user has access to a web page that does not have permission to do so, the spring boot security configuration will be redirected to this jsp file. This jsp file will show the browser’s custom unauthorized access denied error message.

src/main/webapp/WEB-INF/jsp/accessdenied.jsp

<%@ page import ="org.springframework.security.core.*,org.springframework.security.core.context.*" %>
<center>
<h1>Welcome to Spring Boot Access Denied Error Page</h1>

<h2>You are in Spring Boot Access Denied Error page</h2>
<br><a href="/">home</a>
<br><br>
<%
	Authentication auth = SecurityContextHolder.getContext().getAuthentication();

	if (auth != null) {
		out.println("User '" + auth.getName() + "' attempted to access the protected URL: ");
		out.println("<br>auth : "+auth.isAuthenticated());
		out.println("<br>Role : "+auth.getAuthorities());
		out.println("<br>Error Page : "+request.getRequestURL());
	}
%>
</center>


Step 4 – Test the application

403 Forbidden / Access Denied error is simulated by typing a web page url without sufficient permission. Next enter the “http:/localhost:8080/login” login page url. Enter the username as “user” and the password as “password.” After a successful login, the website is redirected to the user dashboard page.

Now, manually type the admin dashboard url in the address bar of the browser and try to access the admin dashboard page. The spring boot security application checks the admin permissions for the admin dashboard. As the user login with the user role, the controller will redirect to the unauthorized access denied error page.

Now type the “http:/localhost:8080/admin / dashboard” url manually in the address bar of the browser.



Leave a Reply