Thursday, 31 January 2013

Spring Security Simple log in app- 1 (without database)

Here we will create a simple login application using Spring MVC & spring security. We will not use database here. First let's make it simple. We will fetch users from our spring security file.

Your folder structure will look like this.



1. Let's start with web.xml file.


<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" id="WebApp_ID" version="3.0">  
  <display-name>Spring-Security-Demo</display-name>  
  <welcome-file-list>  
   <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
  <context-param>  
   <param-name>contextConfigLocation</param-name>  
   <param-value>  
    /WEB-INF/dispatcher-servlet.xml,/WEB-INF/spring-security.xml  
   </param-value>  
  </context-param>  
  <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>  
  <listener>  
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  </listener>  
  <listener>  
   <listener-class>  
    org.springframework.security.web.session.HttpSessionEventPublisher  
   </listener-class>  
  </listener>  
  <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>*.htm</url-pattern>  
  </servlet-mapping>  
 </web-app>  

2. Now lets create spring-security.xml

    Here we will define set of rules for our application like what type of users can access to particular pages. Means, here we will define authentication and authorization for our application.


 <beans:beans xmlns:security="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.1.xsd">  
   
      <!-- By auto-config="true" spring will auto config basic security login -->  
      <security:http auto-config="true">  
   
           <!-- By Intercept-url we can define particular Resource access by particular User Role -->  
           <security:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />  
           <security:intercept-url pattern="/user/**" access="ROLE_USER,ROLE_ADMIN" />  
           <security:intercept-url pattern="/admin/**"     access="ROLE_ADMIN" />  
   
           <!-- By Adding Below Configuration user can add custom login form. -->  
           <security:form-login login-page='/login.htm'  
                default-target-url="/home.htm" authentication-failure-url='/loginFailed.htm' />  
           <security:logout logout-success-url='/login.htm'  
                invalidate-session="true" delete-cookies="true" />  
   
           <!-- in http basic security browser display the login dialog -->  
           <security:http-basic />  
   
           <!-- by below configuration any number of user can login in to same session   
                means any number os user are allowed to login using same username and password -->  
           <security:session-management invalid-session-url="/login.htm" />  
   
           <!-- by below configuration only 3 user can login using same username and password -->  
           <security:session-management invalid-session-url="/login.htm">  
                <!-- by error-if-maximum-exceeded="true" the second login user getting error -->  
                <!-- without error-if-maximum-exceeded="true" first user's session was invalidate -->  
                <security:concurrency-control max-sessions="3" error-if-maximum-exceeded="true" />  
           </security:session-management>  
   
           <!-- Remember Me functionality enabled by using this configuration -->  
           <security:remember-me />  
      </security:http>  
   
      <security:authentication-manager>  
           <!-- You can Define Multiple authentication Provider For Different Resources -->  
           <security:authentication-provider>  
                <!-- by below configuration you manually define the users and password   
                     and Roles for accessing the resource -->  
                <security:user-service>  
                     <security:user name="kuldeep" password="admin" authorities="ROLE_ADMIN" />  
                     <security:user name="vishal" password="user" authorities="ROLE_USER" />  
                </security:user-service>  
           </security:authentication-provider>  
      </security:authentication-manager>  
 </beans:beans>  

Here in intercept-url pattern, give your "url pattern" defined in controller file.
Note: Here "user/**" and "admin/**" are not folder name but the request mapping url that we will give in our controller file.
Providing folder path is very bad bet as it will allow any user to go through.
So always provide controller mapping.


3. Now create a dispatcher servlet named dispatcher-servlet.xml

 After successfully passing from security that we defined, the page request go through the dispatcher servlet. It will redirect to the corresponding page. Here we will define for our View, Prefix as "/WEB-INF/jsp/" means the file should be under WEB-INF/jsp folder, and suffix as ".jsp" means it will return "ReturnedPageName.jsp" file.

 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
      xmlns:context="http://www.springframework.org/schema/context"  
      xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"  
      xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"  
      xmlns:util="http://www.springframework.org/schema/util"  
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd  
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd  
           http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd  
           http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd  
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd  
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">  
   
      <context:annotation-config />  
      <context:component-scan base-package="net.spring.domains" />  
      <context:component-scan base-package="net.spring.controller" />  
   
      <context:property-placeholder location="/WEB-INF/jdbc.properties"></context:property-placeholder>  
   
      <bean id="viewResolver"  
           class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
           <property name="prefix" value="/WEB-INF/jsp/"></property>  
           <property name="suffix" value=".jsp"></property>  
      </bean>  
 </beans>  

4. Now create welcome file named "index.jsp"

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!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=ISO-8859-1">  
 <title>Insert title here</title>  
 </head>  
 <body>  
 <a href="login.htm">Login</a>  
 </body>  
 </html>  

5. Create login page named "login.jsp" under "WEB-INF/jsp/common" folder.

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
   <%@ 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=ISO-8859-1">  
 <title>login</title>  
 </head>  
 <body>  
 <form method="post" action="<c:url value='j_spring_security_check' />">  
 Username : <input name="j_username" /><br>  
 Password : <input type="password" name="j_password"><br>  
 Remember me<input type="checkbox" id="_spring_security_remember_me" name="_spring_security_remember_me">  
   
 <input type="submit" value="Login"><br><br>  
 <a href="register.htm">Register</a>  
 </form>  
 </body>  
 </html>  

Here