How to: Simple maven project with spring security (username and password)

Simple tutorial, how to create a maven web project with username/password authentication based on spring security.

Spring-Security-logo

Prerequisites

  • Java IDE (NetBeans, Eclipse, IntelliJ, …)
  • JDK 7 or newer
  • Maven
  • Tomcat 8

[wp_ad_camp_1]

 Web project creation

  1. Create empty maven web project in your IDE or run command in terminal
    mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee7 -DarchetypeVersion=1.1 -DarchetypeRepository=http://repo.maven.apache.org/maven2 -DgroupId=org.korecky -DartifactId=spring-password -Dversion=1.0 -Dpackage=org.korecky.spring.password -Darchetype.interactive=false --batch-mode archetype:generate
  2. Import created project into your IDE

SpringPassword01

 

Add spring-security dependencies

  1. Open pom.xml file in the project
  2. To the section dependencies add following lines
        <!-- logging -->            
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>    
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>            
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>   
            
        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <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-config</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>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>${javax.annotation.version}</version>
        </dependency>
  3. And to the section properties these lines
        <spring.security.version>3.2.5.RELEASE</spring.security.version>
        <javax.annotation.version>1.0</javax.annotation.version>
        <slf4j.version>1.7.7</slf4j.version>        
        <log4j.version>1.2.17</log4j.version>

[wp_ad_camp_1]

Configure web application

  1. Create new folder “WEB-INF” in “Web Pages” (physical path in the project is /src/main/webapp)
  2. Create in the “WEB-INF” folder file “web.xml” fill it by lines below
    <?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     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>Spring security TEST (password)</display-name>
    
     <welcome-file-list>
     <welcome-file>index.html</welcome-file>
     <welcome-file>index.htm</welcome-file>
     <welcome-file>index.jsp</welcome-file>
     <welcome-file>default.html</welcome-file>
     <welcome-file>default.htm</welcome-file>
     <welcome-file>default.jsp</welcome-file>
     </welcome-file-list>
     
     <!-- WebApplicationContext --> 
     <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> 
     
     <!-- Logging -->
     <listener>
     <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
     </listener> 
    </web-app>
  3. We now configure log4j. Create “log4j.properties”  file in the “WEB-INF” folder and copy/paste lines below
    # log4j configuration file
    log4j.rootCategory=INFO, stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n
    log4j.category.org.springframework=ALL
    log4j.logger.org.springframework.security=DEBUG
    log4j.category.org.springframework.beans.factory=DEBUG

 

Configure spring

  1. Create “applicationContext.xml”  file in the “WEB-INF” folder and copy/paste lines below
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="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.xsd">
    
    <import resource="security.xml"/>
    </beans>
  2. Create “security.xml”  file in the “WEB-INF” folder with content
    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/security"
     xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <http pattern="/resources/**" security="none" />
    <global-method-security />
    <http auto-config="true" use-expressions="true">
     <http-basic />
     <logout logout-url="/logout" />
     <intercept-url pattern="/**" access="isAuthenticated()" /> 
     </http>
    <authentication-manager> 
     <authentication-provider>
     <password-encoder hash="sha-256" /> 
     <user-service>
     <!-- Password encoding: 
     1) Download jacksum.jar tool (e.g. from URL http://sourceforge.net/projects/jacksum/)
     2) Run command: java -jar jacksum.jar -a sha-256 -q "txt:password"
     3) Paste command output into "password" attribute in element "user", default password is "password123"-->
     <user name="testUser" password="ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f" authorities="ROLE_USER, ROLE_ADMIN" />
     </user-service>
     </authentication-provider>
     </authentication-manager>
    </beans:beans>

[wp_ad_camp_1]

 Create test JSP page

  1. Delete file “index.html” in the “Web Pages” folder (physical path in the project is /src/main/webapp)
  2. Create file “index.jsp” instead of “index.html” with content
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
    <!DOCTYPE html>
    <html>
     <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <title>JSP Page</title>
     </head>
     <body>
     <h1>Hello World!</h1> 
     <p>
     <b>User name:</b></br> 
     <%=request.getRemoteUser()%>
     </p>
     <p>
     <b>User principal:</b></br> 
     <%=request.getUserPrincipal()%>
     </p>
     </body>
    </html>

 

Done. We can now test our application.

 

Test

  1. Compile application in your IDE or by command
    mvn clean install
  2. And deploy it to the Tomcat server (from your IDE or copy WAR file from target directory to the webapps in the Tomcat installation)
  3. Run browser and go to the URL http://localhost:8080/spring-password
  4. Application asks you for username and password (if you didn’t change anything it is “testUser” and “password123”)
    SpringPassword02
  5. The index.jsp page is shown after authentication process with your username and credentials
    SpringPassword03

Download

You can download complete source code here: SOURCE CODE ZIP

[wp_ad_camp_1]

 

Leave a Reply

Your email address will not be published. Required fields are marked *