Spring Security Project using Java ConfigurationSpring Framework added Java configuration support in Spring 3.1. In Spring Security, Java configuration was added to Spring Security 3.2 that allows us to configure Spring Security without writing single line of XML. Here, we will create an example that implements Spring Security and configured without using XML. It includes the following steps. Step 1The first step is to create a Spring Security Java configuration. A simple basic Java Configuration is given below. WebSecurityConfig.java This configuration creates a Servlet Filter known as the springSecurityFilterChain. It is responsible for protecting the application URLs, validating submit username and password, redirecting to the login form etc. The above Java Configuration do the following for our application.
Step 2Now, we will register springSecurityFilterChain with the war. To register, Spring Security provides a base class AbstractSecurityWebApplicationInitializer that we need to extend. For Spring MVC application, SecurityWebApplicationInitializer will look like below. SecurityWebApplicationInitializer.java This code will register the springSecurityFilterChain for every URL in our application. Step 3Now, load WebSecurityConfig in our existing ApplicationInitializer and add into the getRootConfigClasses() method. MvcWebApplicationInitializer.java Step 4WebSecurityConfigurerAdapter class provides a configure(HttpSecurity http) method that contains the following default configuration. Default definition looks like below. It is similar to the given XML. This method does the following things.
Step 5Creating a controller to handle user requests. HomeController.java We have one view (.jsp) page index.jsp, it contains the following source code. Our complete project looks like the below. Output: We have a single action in our controller and it can be accessed only by authentic user. So, when we run the application, it prompts for the login credentials. The output is given below. This is default login page provided by the Spring Security, we did not create it. Although we can create our own login page and configure with the application. We will do this in our next topics. Well, now, provide the login credentials to get into the application resource. Spring Security validate user credentials and make sure that user is authentic. Let's see, what happen? If we enter wrong credentials. After click on login button, it throws Bad Credentials error. Now, login with correct credentials. This time credentials are matched and shows our home page (index.jsp). Next TopicSpring Security Login Logout |