Adding Spring Security to J2EE Web App

Spring 3.0.0 Jar Download

Spring Login JSP

<%-- 
    Document   : SpringTest
    Created on : Mar 7, 2012, 4:40:30 PM
    Author     : taher
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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>JSP Page</title>
    </head>
    <body>
        <%if("1".equals(request.getParameter("login_error"))){%><h1 style="color: red;">Login Failure</h1><%}%>
        <form name="f" action="j_spring_security_check" method="POST">
            <table>
                <tr>
                    <td>UserName : </td>
                    <td>
                        <input type='text' name='j_username'/>
                    </td>
                </tr>
                <tr>
                    <td>Password : </td>
                    <td>
                        <input type='password' name='j_password'/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                         <input name="submit" value="Login" type="submit"/>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

ApplicationContext.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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
    <security:http auto-config="true"  >

        <!-- Restrict URLs based on role -->
        <security:intercept-url pattern="/SpringMVC/" access="IS_AUTHENTICATED_ANONYMOUSLY" />

        <security:intercept-url pattern="/common/**" access="ROLE_TEACHER,ROLE_STUDENT,ROLE_CLERK" />

        <security:intercept-url pattern="/teacher/**" access="ROLE_TEACHER" />
        <security:intercept-url pattern="/student/**" access="ROLE_STUDENT" />
        <security:intercept-url pattern="/clerk/**" access="ROLE_CLERK" />

        <!-- Override default login and logout pages -->
        <security:form-login login-page="/SpringTest.jsp"
                             login-processing-url="/j_spring_security_check"
                             default-target-url="/common/commonjsp.jsp"
                             always-use-default-target="true"
                             authentication-failure-url="/SpringTest.jsp?login_error=1" />
        <security:logout  logout-url="/LogOut.jsp" logout-success-url="/SpringTest.jsp" />

        <security:remember-me user-service-ref="user"/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider user-service-ref="user"></security:authentication-provider>
    </security:authentication-manager>

    <bean id="user" class="com.taher.test.controller.SpringLogin">
    </bean>    
</beans>

Spring Login Class


package com.taher.test.controller;

import com.taher.test.model.LoginMaster;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.NoResultException;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


/**
 *
 * @author TaherT
 */
public class SpringLogin implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        System.out.println("I M in loadUser" + username);
        UserDetails user = null;
        Collection<GrantedAuthority> autority = new ArrayList<GrantedAuthority>();
        String pass = "";
        try {
            LoginMaster lm = new LoginMaster();
            List<LoginMaster> loginlst = lm.findLoginDetail(username);
            if (!loginlst.isEmpty()) {
                LoginMaster loginMaster = loginlst.get(0);
                pass = loginMaster.getUserPassword();
                GrantedAuthority teachergrantedAuthority = new GrantedAuthorityImpl("ROLE_TEACHER");
                GrantedAuthority studentgrantedAuthority = new GrantedAuthorityImpl("ROLE_STUDENT");
                GrantedAuthority clerkgrantedAuthority = new GrantedAuthorityImpl("ROLE_CLERK");
                if (loginMaster.getUserType() == 1) {
                    autority.add(teachergrantedAuthority);
                } else if (loginMaster.getUserType() == 2) {
                    autority.add(studentgrantedAuthority);
                } else if (loginMaster.getUserType() == 3) {
                    autority.add(clerkgrantedAuthority);
                }
            }
            user = new User(username, pass, true, true, true, true, autority);
        } catch (NoResultException e) {
            throw new UsernameNotFoundException(e.getLocalizedMessage());
        }
        return user;
    }
}

web.xml

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/ApplicationContext.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <error-page>
        <error-code>403</error-code>
        <location>/NoAccess.jsp</location>
    </error-page>
<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>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>

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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>


<!--    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.-->

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="SpringTest.jsp">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:suffix=".jsp" />
<!--    The index controller.-->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />
</beans>

Folder Structure

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s