Spring Security Project using Java Configuration
Spring 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.
The first step is to create a Spring Security Java configuration. A simple basic Java Configuration is given below.
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.
Now, 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.
This code will register the springSecurityFilterChain for every URL in our application.
Now, load WebSecurityConfig in our existing ApplicationInitializer and add into the getRootConfigClasses() method.
WebSecurityConfigurerAdapter 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.
Creating a controller to handle user requests.
We have one view (.jsp) page index.jsp, it contains the following source code.
Our complete project looks like the below.
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).