Spring Security Using JAVA Configuration In Spring MVC Web Application
We will learn how to add Spring Security to our Spring MVC Web application using JAVA configuration in this blog post instead of XML configuration.
First, we’ll build a simple Spring MVC Web application and secure it with Spring Security. Spring Security’s default login form is discussed in the following part.
POM.XML
Here is the pom.xml
this project with required dependencies:
The Spring Framework version in this application is 5.3.21. We have added Spring MVC, Servlet, and JSP-related dependencies in pom.xml. We are using war as the packaging type, which is why we use the maven-war-plugin to build the application.
Application Configuration — View Resolver
Now, we create a class that will be used to configure ViewResolver
using Java Configuration. Here is the sample XML configuration to configure ViewResolver
using XML configuration in Spring:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
To configure ViewResolver
using JAVA configuration, we need to create ApplicationConfiguration
class in config package:
@EnableWebMvc
provides similar support to<mvc:annotation-driven />
as it is for XML configuration.
We are using JSP as our view technology and keeping our view files in /WEB-INF/view/
.
On the basis of the URL, application control goes to a particular controller and then the controller returns a logical view name. Then it is the view resolver’s job to resolve the logical view name to the actual physical resource.
The InternalResourceViewResolver
is an implementation of theViewResolver
interface. Using setPrefix()
and setSuffix()
, view resolver maps logical view names to actual physical views.
As our prefix is “/WEB-INF/view/” and suffix is “.jsp”, and if the logical view name is “home”, then InternalResourceViewResolver will resolve this as “/WEB-INF/home.jsp”.
As we are using JSP as our view technology, this will be processed by the Servlet/JSP engine.
Initialise Dispatcher Servlet
Now we have to initialize the Spring dispatcher servlet. Here is a sample XML configuration of the dispatcher servlet initializer:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
The dispatcher servlet
is responsible for forwarding/dispatching the request to the appropriate controller method. To initialize our Spring MVC application in the Servlet container environment using JAVA configuration, we create ApplicationDispatherServletInitializer
class in the config package which will extend AbstractAnnotationConfigDispatcherServletInitializer
class.
In this class, we need to configure our Spring MVC Java Configuration file. That is why we have registered previously created ApplicationConfiguration
class in getServletConfigClasses()
method.
Controller
It is time to create a controller class. Create a HomeController
class in the controller package:
Our showHome() method will return home, and based on our configuration, the view resolver will look for home.jsp (as we are using JSP as our view technology) in/WEB-INF/view/. So we must create home.jsp in /WEB-INF/view/.
View
To create the view page, first, create a view directory under/WEB-INF. Then create home.jsp
in the view directory:
Test the Application
Now run this application and put this URL — http://localhost:8080/secure-spring-web-mvc-application/, in the browser:
So our demo Spring MVC Web application is up and running!
Configure Spring Security
Now it is time to secure our MVC application using Spring Security. We need to first update our pom.xml. Here it is:
The Spring Security version for this application is 5.6.6. We have updated the pom.xml with two new dependencies to implement Spring Security — spring-security-web and spring-security-config.
Initialize Application Security
Now, we need to create a security initializer class that will extend AbstractSecurityWebApplicationInitializer
. Here is our ApplicationSecurityInitializer
class which will reside config package:
AbstractSecurityWebApplicationInitializer
helps us to register the DelegatingFilterProxy
to use the Spring Security Filter. When we request any web resource, Spring Security Filter will process those requests and enable user if the user can access the protected web resource.
Configure Application Security
As we are going to customize the security configuration, we will disable auto security configuration and specify the user name and password — that is why we need to create a custom security configuration class by extending WebSecurityConfigurerAdapter
class. So, create ApplicationSecutiryConfiguration
class in config package:
We have annotated this class with @EnableWebSecurity
to disable default security configurations. WebSecurityConfigurerAdapter
provides us several methods and we can override them to customize the security. One of these methods is configure(). As we are going to authenticate users based on their user name and password, we have used AuthenticationManagerBuilder
class to authenticate users. Here, we are using inMemoryAuthentication()
method that will allow us to set hard-coded user credentials. The authentication process which is described here is only for understanding basic Spring Security, we learn to authenticate users with a database.
Test Application with Spring Security
Now run this application again and put this URL — http://localhost:8080/secure-spring-web-mvc-application/ in the browser:
In our application, we did not create any login page, we just configured the Spring Security. This is a built-in login page provided by Spring Security itself to authenticate the user.
We need to provide the username and password that we mentioned in ApplicationSecutiryConfiguration
class to log in to the application. After successful login, we can see our home page. If you provide the wrong credentials, you can see the error on the login page, which means Spring Security will not authenticate you.
You can download the source code from here.
A single clap can have a significant impact. Clap if you found this article useful, and share it with others!👏🌟
Originally published at https://codenicetomedear.blogspot.com.