Spring Security Login Example

Reading Time: 2 minutes

In this tutorial we are covering full of spring security login example but with no database connection. With following tutorials I am thinking to add one with database. To understand basic spring security you may study this example. In this tutorial I used maven and you will find the pom.xml file as well and my favorite IDE IntelliJ. Let us get started with the project

Directory Structure

Selection_015

 

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.example</groupId>
  <artifactId>SpringSecurityFormApp</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SpringSecurityFormApp Maven Webapp</name>
  <url>http://maven.apache.org</url>
    <properties>
        <jdk.version>1.7</jdk.version>
    </properties>
  <dependencies>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>

      <!-- Spring Security -->
      <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-core</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-web</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-config</artifactId>
          <version>3.0.5.RELEASE</version>
      </dependency>
      <!-- JSTL Dependancy -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
      </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>SpringSecurityFormApp</finalName>
      <plugins>
          <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.1</version>
              <configuration>
                  <url>http://localhost:8080/manager/text</url>
                  <server>mytomcat</server>
                  <path>/SpringSecurityFormApp</path>
              </configuration>
          </plugin>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.0</version>
              <configuration>
                  <source>${jdk.version}</source>
                  <target>${jdk.version}</target>
              </configuration>
          </plugin>
      </plugins>
  </build>
</project>

index.jsp

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

loginForm.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>spring security form login demo</title>
</head>
<body>
<table>
    <tr>
        <td valign="top"><c:if test="${not empty param.login_error}">
            <font color="red"> Invalid user name or password, try again.
                <br /><br />
            </font>
        </c:if>
            <form name="login_form"
                  action="<c:url value='j_spring_security_check'/>" method="POST">
                <div>
                    <table width="40%" border="0" cellpadding="0" cellspacing="0">
                        <tr>
                            <td valign="top">
                                <table border="0" cellspacing="0" cellpadding="4" width="40%">
                                    <tr>
                                        <td colspan="2">Custom Login Form
                                            <hr width="100%" size="1" noshade align="left">
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td width="80">Username</td>
                                        <td valign="top" align="left">
                                            <input type='text'
                                                   id='username'
                                                   name='j_username'
                                                   value='<c:if test="${not empty param.login_error}">
                                                     <c:out value="${SPRING_SECURITY_LAST_USERNAME}"/>
                                                   </c:if>' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td width="80">Password</td>
                                        <td valign="top" align="left"><input type='password'
                                                                             name='j_password' size="30" maxlength="30"></td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td><input type="submit" value="Submit" /></td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </div>
            </form></td>
    </tr>
</table>
</body>
</html>

web.xml

<?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/j2ee/web-app_2_4.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
            http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">

    <display-name>SpringSecurityDemo</display-name>
    <description>SpringSecurityDemo</description>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/dispatcher-servlet.xml,
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <!-- 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>

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-3.0.xsd
            http://www.springframework.org/schema/security
            http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">

    <http auto-config="true">
        <intercept-url pattern="/loginForm.jsp" filters="none"/>
        <intercept-url pattern="/**" access="ROLE_USER" />
        <form-login login-page="/loginForm.jsp"
                    default-target-url="/login.do" always-use-default-target="true"
                    authentication-failure-url="/loginForm.jsp?login_error=1" />
        <logout logout-success-url="/loginForm.jsp" />
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="tugrul" password="12345"
                      authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

dispatcher-servlet.xml

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.example.controller" />
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>Message : ${message}</h1>   
<a href="<c:url value="/j_spring_security_logout" />" > Logout</a>
</body>
</html>

WelcomeController.java

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class WelcomeController {
    @RequestMapping(value="/login.do", method = RequestMethod.GET)
    public ModelAndView printWelcome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", "Spring security allows you");
        modelAndView.setViewName("login");
        return modelAndView;
    }
}

You may now deploy the application to the server and test it