Spring Security hello world example

In this post, we will see how to apply basic spring security to spring mvc hello world example.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example
If you want to secure your spring web application , you just need to configure some files to make it happen using spring security. We will apply login security on hello world example. So when only authorised users will be able to access hello world message.

Here are steps to apply basic spring security on spring mvc hello world example.

Step 1: 
Create Spring mvc hello world example named SpringSecurityHelloWorldExample . It will create basic spring mvc application.

Step 2: 
Add spring security to pom.xml. You need to add following dependencies to the pom.
pom.xml 
<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.arpit.java2blog</groupId>
 <artifactId>SpringSecurityHelloWorlExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringSecurityHelloWorldExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
   <!-- Spring Security -->
               <dependency>
               <groupId>org.springframework.security</groupId>
               <artifactId>spring-security-core</artifactId>
               <version>${security.version}</version>
               </dependency>

               <dependency>
               <groupId>org.springframework.security</groupId>
               <artifactId>spring-security-web</artifactId>
               <version>${security.version}</version>
               </dependency>

               <dependency>
               <groupId>org.springframework.security</groupId>
               <artifactId>spring-security-config</artifactId>
               <version>${security.version}</version>
               </dependency>

               <dependency>
               <groupId>jstl</groupId>
               <artifactId>jstl</artifactId>
               <version>1.2</version>
               <scope>provided</scope>
               </dependency>
 </dependencies>
 <build>
  <finalName>SpringSecurityHelloWorlExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <security.version>4.0.3.RELEASE</security.version>
  <jdk.version>1.7</jdk.version>
 </properties>
 
 
</project>
Step 3: 
Modify hello.jsp in /WEB-INF/ folder
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body>
${message}


<c:url value="/j_spring_security_logout" var="logoutUrl" />
<a href="${logoutUrl}">Log Out</a>
 
</body>
</html>

Step 4:  
Now we need to add spring configuration xml. Create a file named spring-security.xml.
<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-4.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <http auto-config="true" use-expressions="true">
      <intercept-url pattern="/resources/**" access="permitAll" />

       <intercept-url pattern="/hello*" access="hasRole('ROLE_ADMIN')" />
<logout logout-success-url="/" logout-url="/j_spring_security_logout" />
   <csrf disabled="true"/>
    </http>

    <authentication-manager>
      <authentication-provider>
        <user-service>
            <user name="java2blog" password="java123" authorities="ROLE_ADMIN" />
           
        </user-service>
      </authentication-provider>
    </authentication-manager>

</beans:beans>

intercept-url configure for which pattern what kind of security is configured. For example: If http request url has pattern /hello*(hello.jsp,helloworld.html), it will be accessed to ROLE_ADMIN only.

We have hardcoded username(java2blog) and password(java123)   in authentication manager, so if user provides correct credential for admin then only he will be able to access helloworld.htm/.

We have not configured any login page here, so spring security will generate one for us.

Step 5: We need to change in web.xml to configure spring security.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>springmvc-dispatcher</servlet-name>
    <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
   <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   /WEB-INF/springmvc-dispatcher-servlet.xml,
   /WEB-INF/spring-security.xml
  </param-value>
 </context-param>
 
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <!-- Spring Security -->
 <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>
Here we have used DelegatingFilterProxy which intercepts http request and pass it to springSecurityFilterChain. springSecurityFilterChain is a bean created by spring with http element used in spring-security.xml. It maintains list of all filters and is responsible for chain of filters.

We are done with changes required for spring security.

Step 6:
It's time for maven build.
   
Provide goals as clean install (given below) and click on run


Run the application


Step 7:
Right click on project -> run as -> run on server
Select apache tomcat and click on finish

   You will see below screen:


When you click on above link, you will get following login page.


If you put wrong password and try to login, you will get below screen


If you put correct user id and password



Bingo !! you have logged in successfully.


When you click on logout, you will be back to first screen.

Download source code:

click to begin
20KB .zip
Please comment if you have any issues with above post.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012