Spring security Hello world project


Tools and Technologies used

1) Eclipse IDE Mars Release (4.5.0)

2) Java 8

3) Spring framework 3.2

4) Spring security 3.2

5) Tomcat 8


Step 1

Create a new maven project from eclipse

SpringSecurity_createProj1

SpringSecurity_createProj2

SpringSecurity_createProj3

SpringSecurity_CreateProject4

SpringSecurity_CreateProject5


Step 2

Add Tomcat server in your eclipse

SpringSecurity_CreateProject6

SpringSecurity_CreateProject7

Step 3

Add all the spring security and spring mvc dependencies into the pom file.

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>com.kb</groupId>
  5.   <artifactId>SpringSecurityHelloWorld</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringSecurityHelloWorld Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.  
  11.   <properties>
  12.         <org.springframework.version>3.2.7.RELEASE</org.springframework.version>
  13.         <spring-security.version>3.2.7.RELEASE</spring-security.version>
  14.     </properties>
  15.   <dependencies>
  16.     <dependency>
  17.       <groupId>junit</groupId>
  18.       <artifactId>junit</artifactId>
  19.       <version>3.8.1</version>
  20.       <scope>test</scope>
  21.     </dependency>
  22.      <!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context, spring-web -->
  23.         <dependency>
  24.             <groupId>org.springframework</groupId>
  25.             <artifactId>spring-webmvc</artifactId>
  26.             <version>${org.springframework.version}</version>
  27.         </dependency>
  28.          
  29.         <!-- Spring Security Dependencies -->
  30.         <dependency>
  31.             <groupId>org.springframework.security</groupId>
  32.             <artifactId>spring-security-core</artifactId>
  33.             <version>${spring-security.version}</version>
  34.          </dependency>
  35.          <dependency>
  36.             <groupId>org.springframework.security</groupId>
  37.             <artifactId>spring-security-web</artifactId>
  38.             <version>${spring-security.version}</version>
  39.           </dependency>
  40.           <dependency>
  41.             <groupId>org.springframework.security</groupId>
  42.             <artifactId>spring-security-config</artifactId>
  43.             <version>${spring-security.version}</version>
  44.           </dependency>
  45.   </dependencies>
  46.   <build>
  47.     <finalName>SpringSecurityHelloWorld</finalName>
  48.     <plugins>
  49.             <plugin>
  50.                 <groupId>org.apache.maven.plugins</groupId>
  51.                 <artifactId>maven-compiler-plugin</artifactId>
  52.                 <version>2.5.1</version>
  53.                 <configuration>
  54.                     <source>1.8</source>
  55.                     <target>1.8</target>
  56.                 </configuration>
  57.             </plugin>
  58.         </plugins>
  59.   </build>
  60. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.kb</groupId>
  <artifactId>SpringSecurityHelloWorld</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringSecurityHelloWorld Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
        <org.springframework.version>3.2.7.RELEASE</org.springframework.version>
        <spring-security.version>3.2.7.RELEASE</spring-security.version>
    </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context, spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
         
        <!-- Spring Security Dependencies -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring-security.version}</version>
         </dependency> 
         <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring-security.version}</version>
          </dependency> 
          <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring-security.version}</version>
          </dependency>
  </dependencies>
  <build>
    <finalName>SpringSecurityHelloWorld</finalName>
    <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
  </build>
</project>

Step 4

Modify web.xml file

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>Spring MVC Application</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.             /WEB-INF/spring-security.xml
  16.         </param-value>
  17.         </init-param>
  18.         <load-on-startup>1</load-on-startup>
  19.     </servlet>
  20.     <servlet-mapping>
  21.         <servlet-name>mvc-dispatcher</servlet-name>
  22.         <url-pattern>/</url-pattern>
  23.     </servlet-mapping>
  24.  
  25.     <listener>
  26.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  27.     </listener>
  28.  
  29.     <!-- Loads Spring Security configuration file -->
  30.     <context-param>
  31.         <param-name>contextConfigLocation</param-name>
  32.         <param-value>
  33.             /WEB-INF/spring-mvc.xml,
  34.             /WEB-INF/spring-security.xml
  35.         </param-value>
  36.     </context-param>
  37.  
  38.     <!-- Spring Security filter -->
  39.     <filter>
  40.         <filter-name>springSecurityFilterChain</filter-name>
  41.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  42.     </filter>
  43.  
  44.     <filter-mapping>
  45.         <filter-name>springSecurityFilterChain</filter-name>
  46.         <url-pattern>/*</url-pattern>
  47.     </filter-mapping>
  48.  
  49. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Spring MVC Application</display-name>

	<!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-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.xml,
			/WEB-INF/spring-security.xml
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Loads Spring Security configuration file -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-mvc.xml,
			/WEB-INF/spring-security.xml
		</param-value>
	</context-param>

	<!-- Spring Security filter -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

We all know that filters are defined in web.xml to perform something before the actual request is happening.

Similarly org.springframework.web.filter.DelegatingFilterProxy filter is used to pass request to Spring authentication mechanism before being processed.
This filter checks for the url pattern defined for it and passes all the requests matching that pattern to spring security mechanism.

In the above case, pattern is /*, so all the requests will be filtered by this filter and pass through spring security mechanism.

Step 5

Create Spring-mvc xml file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.      
  16.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  17.         <property name="prefix" value="/WEB-INF/pages/" />
  18.         <property name="suffix" value=".jsp" />
  19.     </bean>
  20. </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 
    <context:component-scan base-package="com.kb.*" />
    <mvc:annotation-driven />
     
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Step 6

Create Spring-security.xml

  1. <beans:beans xmlns="http://www.springframework.org/schema/security"
  2.   xmlns:beans="http://www.springframework.org/schema/beans"
  3.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.   xsi:schemaLocation="http://www.springframework.org/schema/beans
  5.          http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  6.          http://www.springframework.org/schema/security
  7.          http://www.springframework.org/schema/security/spring-security-3.2.xsd">
  8.            
  9.     <http auto-config='true'>
  10.       <intercept-url pattern="/secured/*" access="ROLE_USER" />
  11.     </http>
  12.        
  13.     <authentication-manager>
  14.       <authentication-provider>
  15.         <user-service>
  16.           <user name="kb" password="kb1234" authorities="ROLE_USER" />
  17.         </user-service>
  18.       </authentication-provider>
  19.     </authentication-manager>  
  20.            
  21. </beans:beans>
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.2.xsd">
           
    <http auto-config='true'>
      <intercept-url pattern="/secured/*" access="ROLE_USER" />
    </http>
       
    <authentication-manager>
      <authentication-provider>
        <user-service>
          <user name="kb" password="kb1234" authorities="ROLE_USER" />
        </user-service>
      </authentication-provider>
    </authentication-manager>   
           
</beans:beans>

< intercept-url > tag defines the pattern to configure all the URLs which needs to be secured.
In our case, /secured/* means, all the URLS which has /secured at the beginning will be secured.
And access attribute defines the user’s role who can access these secured URLs.

auto-config=’true’ provides the Auto login form , BASIC Authentication and logout services. By default this attribute will be false.

authentication-manager – is used to manage the authentication of the request based on the Authentication provider.

authentication-provider – is used to define the authentication mechanism and it could be any one of these
jdbc-user-service
ldap-user-service
password-encoder
user-service

I have implemented using user-service mechanism with username and password provided in security file directly.
We can also use DB call with the query to authenticate the in user.
We can also use our own class/third party system to define authentication mechanism.

Step 7

Let’s create public hello world jsp page

  1. <html>
  2. <head>
  3.        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  4. <title>Insert title here</title>
  5. </head>
  6. <body>
  7.      <h3>Hello World!</h3>
  8.      <h4>${message}</h4>
  9. </body>
  10. </html>
<html>
<head>
       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
     <h3>Hello World!</h3>
     <h4>${message}</h4>
</body>
</html>

Step 8

Let’s create secured hello world jsp page

  1. <html>
  2. <head>
  3.      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  4. <title>Insert title here</title>
  5. </head>
  6. <body>
  7.      <h3>Hello World!</h3>
  8.      <h4>${message}</h4>
  9. </body>
  10. </html>
<html>
<head>
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
     <h3>Hello World!</h3>
     <h4>${message}</h4>
</body>
</html>

Step 9

Build the project ->Right click on project and select maven-install

SpringSecurity_BuildProject

Step 10

Deployment of our application

Now go to the target folder of project and copy the war file SpringSecurityHelloWorld.war

E:\workspace\Spring-security-ws\SpringSecurityHelloWorld\target\SpringSecurityHelloWorld.war

Paste it in the tomcat’s webapps folder
E:\workspace\Spring-security-ws\SpringSecurityHelloWorld\target

Step 11

Start the server

Right click on server and click on start as shown below

SpringSecurity_ServerSrtart

Step 12

Open browser

Type http://localhost:8080/ and see whether server window opens
If not then double click on server in eclipse and keep server location as below

SpringSecurity_ServerWindow

Step 13

Access the below url

http://localhost:8080/SpringSecurityHelloWorld/public/pages

SpringSecurity_Output_welcomePage

Step 14

Now try to access secured url

http://localhost:8080/SpringSecurityHelloWorld/secured/pages

You should get default spring login form

SpringSecurity_DefaultForm

Notice here that secured page is not accessible directly, we need to provide valid credentials to access this page.
Spring has displayed its own login form, please enter valid user name and password and then access secured pages.

Step 15

Enter invalid credentials and see the output

SpringSecurity_Invalid_Credentials

Step 16

Enter valid credentials which are as below

Username – kb
Password – kb1234

SpringSecurity_valid_Credentials

Download this project SpringSecurityHelloWorld.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on