Removing default model attributes in the URL in Spring MVC while redirecting

Removing default model attributes in the URL in Spring MVC while redirecting

Recently I have come across a problem regarding page redirection. The application I was working on is using Spring security and also Spring MVC.

The problem was that when the user tries to access the /login.html the login page will be displayed if he is not logged in, but if he is already logged in then there was a problem with the URL being shown in the browser i.e. login.html (though his relevant page content is shown) as internally there was a jsp forward.

Jsp forward will not change the URL in the browser address bar. Only redirect will change the address as the browser will be asked to send another request to the server.

<div>
    <auth:authorize access="hasRole('ROLE_ADMIN')">
        <jsp:forward page="/admin/home.html"/>
    </auth:authorize>

    <auth:authorize access="hasRole('ROLE_USER')">
        <jsp:forward page="/user.html"/>
    </auth:authorize>
</div>

The above configuration from a JSP was used to forward the user to his relevant page. Since it was a jsp forward, the URL in the browser address bar was not changing.

To solve this problem I had to use Spring’s RedirectView class. So, this article shows the usage of that class and how we can avoid the default model attributes not being shown in the URL.

When we use the RedirectView class and set and return the view, it actually works fine and redirects to the specified view with the change in the URL of the browser.

But there is a caveat. It actually exposes the default model attributes in the URL like the following

http://localhost:8081/app/admin.html?total=48&loggedInUserRoles=207.

The data after ? is exposed in the URL as it the default model attribute in my application.

So, to strip off the extra data from the URL we have to set the exposeModelAttributes to false as in the following code.

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public View login(HttpServletRequest request) throws IOException {

        //Get the Spring Security authentication object
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        RedirectView view;
        String url = null;

        //Check if the user is already logged in (except the anonymous user)
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            //User is logged in
            List userRoles = AuthenticationUtils.getUserRoles();
            if (userRoles.contains("ROLE_ADMIN")) {
                url = "./admin/home.html";
            } else if (userRoles.contains("ROLE_USER")) {
                url = "./user.html";
            }
        }

        //If the user is not logged in, the url variable will be null
        //If the user is not logged in, send him to the application root, where login page will be shown
        if (url == null) {
            url = "/" + request.getContextPath();
        }

        view = new RedirectView(url);
        view.setExposeModelAttributes(false);
        return view;
    }

 

The line view.setExposeModelAttributes(false) removes the default model attributes from the URL.

Hope this article has helped you and wish you a happy coding.

Reference:

http://stackoverflow.com/questions/31187747
http://stackoverflow.com/questions/13247239

Rajasekhar
Java Developer
Helical IT Solutions

Session Management in Spring Security

Before we go to spring security session management let first understand what is session and why session is required.

Whenever we connect to any web server through URL, we use browser as client which uses a HTTP protocol for communication between browser and server. HTTP is a “stateless” protocol which means each time client receives a web page, the client opens a separate connection to web server and server automatically does not keep any record of previous client request that means for web server every request is a new request to process and they can’t identify if it’s coming from client that has been sending request previously. But sometime in web applications, we should know who client is and process the request accordingly.

Session is a conversional state between client and server and it consists of multiple request and response between client and server. Since HTTP protocol and web server both are “stateless” the only way to maintain a session is when some unique information about session like session id is passed between server and client in every request and response. In other words session is unique Id created by container to identify the user from whom the request in coming in

spring security.

Now we jump to how is session management takes place in spring security.

When is session created?
We can control exactly when our sessions get created and how spring security interact with it.
1. always – a session will always be created if one already does not exist
2. ifRequired – a session is created if required (Default).
3. never – a framework will never create a session itself. But it will use one if it already exists.
4. Stateless – no session is created or used by spring security.

<http create-session=”ifRequired”>….</http>

It is very important to understand that this configuration only controls what spring security does – not the entire application. Spring security may not create the session in we instruct it not to, but our application may!

By default spring security will create session when it needs one. This is ”ifRequired”
For a more “stateless” application, the “never” option will ensure that spring security itself will not create any session; however if application creates one, the spring security makes use of it.

Finally, the strictest session creation option – “stateless” – is guarantee that the application will not create any session at all.

Concurrent Session Control
When a user that is already authenticated tries to authenticate again, the application can deal with that event in one of a few ways. It can either invalidate the active session of the user and authenticate the user again with a new session, or allow both sessions to exist concurrently.

First step in enabling the concurrent session-control support is to add the following listener in the web.xml:

<listener>

<listener-class>

org.springframework.security.web.session.HttpSessionEventPublisher

</listener-class>

</listener>

 

This is essential to make sure that the Spring Security session registry is notified when the session is destroyed.

To enable the scenario which allows multiple concurrent sessions for the same user the element should be used in the XML configuration:

<http …>

<session-management>

<concurrency-control max-sessions=”3″ />

</session-management>

</http>
Session Timeout

After the session has timed out, if the user sends a request with an expired session id, they will be redirected to an URL configurable via the namespace:
<session-management>

<concurrency-control expired-url=”/sessionExpired.html” … />

</session-management>

Similarly, if the user sends a request with a session id which is not expired, but entirely invalid, they will also be redirected to a configurable URL:
<session-management invalid-session-url=”/invalidSession.html”>

</session-management>

Passing the extra parameter from login page Spring Security

We have implemented spring security with database using hibernate in previous post.
You can have a look at the previous post from the following link http://helicaltech.com/spring-security-with-hibernate/
We had seen spring security supports username and password from login page by default.
In this post we will learn how to pass extra parameter from login page to spring security.

We know how to add spring and spring security jar’s in application class path using maven and adding dependencies in pom.xml file. By default spring submit the page to j_spring_security_check which use UsenamePasswordAuthenticationFilter for authenticating user which extends the AbstractAuthenticationProcessingFilter class.

    Below are the steps for implementation

Step 1. Create the class which extends the UsenamePasswordAuthenticationFilter and override the two methods attemptAuthentication and obtainUsername

public Authentication attemptAuthentication(HttpServletRequest req,HttpServletResponse res)
throws AuthenticationException{
}
public String obtainUsername(HttpServletRequest req){
}

attemptAuthentication method takes the HttpServletRequest and HttpServletResponse arguments and return the Authentication object and obtainUsername takes the HttpServletRequest argument and return the String which contain the username and extra parameter passed by the login page with delimiter separator.
Below is class with business logic I chose the class name as ExtInpuParam.

public class ExtInpuParam extends
UsernamePasswordAuthenticationFilter {
private static final Logger logger = LoggerFactory
.getLogger(PreUsernamePasswordAuthenticationFilter.class);
private String extraParameter = "j_organization";
private String delimiter = ":";
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
logger.debug("Attempting for authentication. " + "j_username = "
+ request.getParameter("j_username") + ", j_password = "
+ request.getParameter("j_password"));
return super.attemptAuthentication(request, response);
}
@Override
protected String obtainUsername(HttpServletRequest request) {
String username = request.getParameter(getUsernameParameter());
logger.debug("username = " + username);
String extraInput = request.getParameter(getExtraParameter()) == null ? ""
: request.getParameter(getExtraParameter());
logger.debug("extraInput = " + extraInput);
String combinedUsername = "";
String extParam = extraInput.trim();
logger.debug("extParam = " + extParam);
if (extParam.length() == 0) {
combinedUsername = username;
} else {
combinedUsername = username + getDelimiter() + extraInput;
}
logger.debug("returning combinedUsername = " + combinedUsername);
return combinedUsername;
}
/**
* @return The parameter name which will be used to obtain the extra input
* from the login request
*/
public String getExtraParameter() {
return this.extraParameter;
}

/**
* @param extraParameter
* The parameter name which will be used to obtain the extra
* input from the login request
*/
public void setExtraParameter(String extraParameter) {
this.extraParameter = extraParameter;
}

/**
* @return The delimiter string used to separate the username and extra
* input values in the string returned by
* obtainUsername()
*/
public String getDelimiter() {
return this.delimiter;
}

/**
* @param delimiter
* The delimiter string used to separate the username and extra
* input values in the string returned by
* obtainUsername()
*/
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}

}

I passed the extra parameter name as j_organization from login page and adding delimiter “:” with username obtainUsername method will return the uername with extra parameter and “:” separator. In userDetails class you will get the username and extra parameter.

Step 2. Add j_organization instance field with getter and setter in user model class.

Step 3.
Please refer to the code in the below snapshots for the steps to be followed for Step No 3.
spring security

spring security 2

Step 4. Login.jsp page

<form name='loginForm'
action="" method='POST'>

Organization:
User:
Password:

Thankyou
Muqtar Ahmed
Helical IT Solutions

Spring Security with Hibernate

Today I’m going to talk about spring security with hibernate.  Let download the required jar and set these jars in class path of application.

  1. spring  3.2.8 RELEASE
  2. spring security 3.2.8 RELEASE
  3. hibernate 3.3.0.ga

Let’s implements the spring security we have 4 xml configuration files as below

  1. web.xml
  2. spring-databse.xml
  3. dispatcher -mvc-servlet.xml
  4. spring-security.xml

 

  1. our web.xml file content will be

<web-app id=”WebApp_ID” version=”2.4″

xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>

<display-name>Helical Demo</display-name>

<!– Spring MVC –>

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

 

<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-database.xml,

/WEB-INF/spring-security.xml

</param-value>

</context-param>

<filter>

<filter-name>hibernateFilter</filter-name>

<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>

<init-param>

<param-name>singleSession</param-name>

<param-value>true</param-value>

</init-param>

</filter>

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

  1. spring-databse.xml

<beans xmlns=”http://www.springframework.org/schema/beans”

xmlns:context=”http://www.springframework.org/schema/context”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:mvc=”http://www.springframework.org/schema/mvc”

xmlns:p=”http://www.springframework.org/schema/p” xmlns:tx=”http://www.springframework.org/schema/tx”

xsi:schemaLocation=”

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd”>

<context:annotation-config />

<context:component-scan base-package=“com.helical.demo” />

 

<bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource”

destroy-method=“close”>

<property name=“driverClassName” value=“com.mysql.jdbc.Driver” />

<property name=“url” value=“jdbc:mysql://localhost:3306/test” />

<property name=“username” value=“root” />

</bean>

<bean id=“sessionFactory”

class=“org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean”>

<property name=“dataSource” ref=“dataSource” />

<property name=“packagesToScan”>

<list>

<value>com.helical.demo.model</value>

</list>

</property>

<property name=“configurationClass”>

<value>org.hibernate.cfg.AnnotationConfiguration</value>

</property>

<property name=“hibernateProperties”>

<props>

<prop key=“hibernate.dialect”>org.hibernate.dialect.MySQL5Dialect</prop>

<prop key=“hibernate.show_sql”>true</prop>

</props>

</property>

</bean>

<tx:annotation-driven />

<bean id=“transactionManager”

class=“org.springframework.orm.hibernate3.HibernateTransactionManager”>

<property name=“sessionFactory” ref=“sessionFactory” />

</bean>

</beans>

  1. our dispatcher -mvc-servlet.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans”

xmlns:context=”http://www.springframework.org/schema/context”

xmlns:mvc=”http://www.springframework.org/schema/mvc”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xmlns:util=”http://www.springframework.org/schema/util”

xsi:schemaLocation=”

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd”>

<context:annotation-config />

<!– <context:annotation-driven/> –>

<context:component-scan base-package=”com.helical.demo.controller” />

 

<bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>

<property name=”prefix”>

<value>/WEB-INF/jsp/</value>

</property>

<property name=”suffix”>

<value>.jsp</value>

</property>

</bean>

</beans>

4. 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.1.xsd”>

<!– We will be defining all security related configurations in this file –>

<http auto-config=“true” use-expressions=“true”>

<intercept-url pattern=“/**” access=“isAuthenticated()”/>

<intercept-url pattern=“/admin**” access=“hasRole(‘ROLE_ADMIN’)”/>

<intercept-url pattern=“/user**” access=“hasRole(‘ROLE_USER’)” />

<!– this means all URL in this app will be checked if user is authenticated –>

<form-login/><!–  We will just use the built-in form login page in Spring –>

<logout logout-url=“/logout” logout-success-url=“/index”/><!–  the logout url we will use in JSP –>

</http>

<beans:bean id=“daoAuthenticationProvider” class=“org.springframework.security.authentication.dao.DaoAuthenticationProvider”>

<beans:property name=“userDetailsService” ref=“userDetailsService” ></beans:property>

</beans:bean>

<beans:bean id=“authenticationManager” class=“org.springframework.security.authentication.ProviderManager”>

<beans:property name=“providers”>

<beans:list>

<beans:ref local=“daoAuthenticationProvider”/>

</beans:list>

</beans:property>

</beans:bean>

<authentication-manager>

<authentication-provider user-service-ref=“userDetailsService”>

</authentication-provider>

</authentication-manager>

</beans:beans>

Create the tables in DB

  1. user
  2. user_role
  3. role

 

CREATE  TABLE user_role (

user_id INT(11) NOT NULL

role_id INT(11) NOT NULL,

));

CREATE  TABLE role (

id INT(11) NOT NULL

role_name VARCHAR(100) NOT NULL,

PRIMARY KEY(id));

CREATE  TABLE user (

id INT(11) NOT NULL

username VARCHAR(45)NOTNULL,

password VARCHAR(60)NOTNULL,

status VARCHAR(10) NOTNULL,

PRIMARY KEY(id));

Let insert  the values in tables

INSERTINTO user(username,password,status) VALUES(‘ADMIN’,’ADMIN’,‘ACTIVE’);INSERTINTO role(role_name) VALUES(‘ROLE_ADMIN’);INSERTINTO user_role(user_id,role_id) VALUES(1,1);

Create the packages

Com.helical.demo.model and create a class User.java this is entity class and Role.java and enum UserStatus

 

package com.helical.demo.model;

 

publicenum UserStatus {

ACTIVE,

INACTIVE;

}

package com.helical.demo.model;

import java.io.Serializable;

import java.util.List;

import javax.persistence.Entity;

import javax.persistence.EnumType;

import javax.persistence.Enumerated;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.JoinTable;

import javax.persistence.ManyToMany;

@Entity

public class User implements Serializable{

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

private int id;

private String username;

private String password;

@ManyToMany

@JoinTable(name=”user_role”,

joinColumns=@JoinColumn(name=”user_id”),

inverseJoinColumns=@JoinColumn(name=”role_id”))

private List<Role> roles;

@Enumerated(EnumType.STRING)

private UserStatus status;

public User(){}

 

public User(int id, String username, String password, List<Role> roles,

UserStatus status) {

super();

this.id = id;

this.username = username;

this.password = password;

this.roles = roles;

this.status = status;

}

 

public int getId() {

return id;

}

 

public void setId(int id) {

this.id = id;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public List<Role> getRoles() {

return roles;

}

public void setRoles(List<Role> roles) {

this.roles = roles;

}

 

public UserStatus getStatus() {

return status;

}

public void setStatus(UserStatus status) {

this.status = status;

}

}

Create a Role class

package com.helical.demo.model;

import java.util.List;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.ManyToMany;

@Entity

public class Role {

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

private int id;

private String role_name;

@ManyToMany(mappedBy = “roles”)

private List<User> users;

public Role(){}

public Role(int id, String roleName, List<User> users) {

super();

this.id = id;

this.role_name = roleName;

this.users = users;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getRole_name() {

return role_name;

}

public void setRole_name(String role_name) {

this.role_name = role_name;

}

public List<User> getUsers() {

return users;

}

public void setUsers(List<User> users) {

this.users = users;

}

}

Create a Dao pakage as com.helical.demo.dao create a interface and class as follows

package com.helical.demo.dao;

import java.util.List;

import com.helical.demo.model.User;

public interface UserDao {

User findUserByName(String username);

}

package com.helical.demo.dao;

 

import java.util.List;

 

import org.hibernate.Criteria;

import org.hibernate.SessionFactory;

import org.hibernate.criterion.Restrictions;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

import com.helical.demo.dao.UserDao;

import com.helical.demo.model.User;

@Repository

public class UserDaoImpl implements UserDao {

@Autowired

private SessionFactory session;

@Override

public User findUserByName(String username) {

Criteria criteria = session.getCurrentSession().createCriteria(User.class);

criteria.add(Restrictions.eq(“username”, username));

return (User) criteria.uniqueResult();

}

}

Create a pakage com.helical.demo.service and create a class as follows

package com.helical.demo.service;

import java.util.ArrayList;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import com.helical.demo.dao.UserDao;

import com.helical.demo.model.Role;

import com.helical.demo.model.User;

import com.helical.demo.model.UserStatus;

@Service(“userDetailsService”)

public class UserDetailsServiceImpl implements UserDetailsService {

@Autowired

private UserDao userDao;

@Override

@Transactional(readOnly = true)

public UserDetails loadUserByUsername(String username)

throws UsernameNotFoundException {

User user = userDao.findUserByName(username); //our own User model class

if(user!=null){

String password = user.getPassword();

//additional information on the security object

boolean enabled = user.getStatus().equals(UserStatus.ACTIVE);

boolean accountNonExpired = user.getStatus().equals(UserStatus.ACTIVE);

boolean credentialsNonExpired = user.getStatus().equals(UserStatus.ACTIVE);

boolean accountNonLocked = user.getStatus().equals(UserStatus.ACTIVE);

//Let’s populate user roles

Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

for(Role role : user.getRoles()){

authorities.add(new SimpleGrantedAuthority(role.getRole_name()));

//authorities.add(new GrantedAuthorityImpl(role.getRole_name()));

}

//Now let’s create Spring Security User object

org.springframework.security.core.userdetails.User securityUser = new

org.springframework.security.core.userdetails.User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);

return securityUser;

}else{

throw new UsernameNotFoundException(“User Not Found!!!”);

}

}

}

Note This class implements the UserDetailsService Interface which is provided by the spring which has only one method loadUserByUsername which take string argument as return the UserDetails Object and also note that at the top of this class we used @Service(“UserDetailsService”) to tell the spring container this class is get loaded when any request is come in to application. We specified this class in spring-security.xml configuration file above as

<authentication-manager>

<authentication-provider user-service-ref=“userDetailsService”>

</authentication-provider>

</authentication-manager>

 

Finally Create the controller for our Application

@Controller

public class MainController  {

@RequestMapping(value = { “/”, “/index**” }, method = RequestMethod.GET)

public ModelAndView defaultPage() {

ModelAndView model = new ModelAndView();

model.addObject(“title”, “Redirect to Admin page”);

model.addObject(“message”, “This page is for ROLE_ADMIN only!”);

model.setViewName(“admin”);

return model;

}

}

Create admin.jsp which is redirected once admin login

\src\main\webapp\WEB-INF\jsp\admin.jsp

 

<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>

<%@ taglib uri=”http://www.springframework.org/security/tags” prefix=”sec”%>

 

<%@page session=”true”%>

<html>

<body>

<h1>Title : ${title}</h1>

<h1>Message : ${message}</h1>

<h1>Welcome! <sec:authentication property=”principal.username”/></h1><br />

 

<c:url value=”/j_spring_security_logout” var=”logoutUrl” />

<form action=”${logoutUrl}” method=”post” id=”logoutForm”>

<input type=”hidden” name=”${_csrf.parameterName}”

value=”${_csrf.token}” />

</form>

<script>

function formSubmit() {

document.getElementById(“logoutForm”).submit();

}

</script>

 

<c:if test=”${pageContext.request.userPrincipal.name != null}”>

<h2>

Welcome : ${pageContext.request.userPrincipal.name} | <a

href=”javascript:formSubmit()”> Logout</a>

</h2>

</c:if>

</body>

</html>

BY Muqtar Ahmed
Helical IT Solutions

Spring Security

Spring Security Spring provides a configurable framework for implementing authentication and authorization for an application. The security framework provides ways to login and logout from an application. It also provides authentication at view level and method level. It can also provide you with the login page. Following are the provided by spring security framework • Provide capabilities for login and logout.
• Control access to a link based on the role of the user.
• Provide the ability to hide certain portion of the page if user does not have appropriate privileges.
• Link to database or LDAP for authentication.
To implements spring security we need three jar mainly spring-security-core, spring-security-web and spring-security-config download these jar and set in application class path.

\src\main\webapp\WEB-INF\web.xml

We need to add security configuration and spring-security filter chain in web.xml to tell the container about security setting and configuration.

<web-app id=“WebApp_ID” version=“2.4”

xmlns=“http://java.sun.com/xml/ns/j2ee” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=“http://java.sun.com/xml/ns/j2ee

    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>

<display-name>Helical Project</display-name>

<!– Spring MVC –>

<servlet>

<servlet-name>mvc-dispatcher</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>mvc-dispatcher</servlet-name>

<url-pattern>/</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/mvc-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>

\src\main\webapp\WEB-INF\mvc-dispatcher-servlet.xml

Here is simple spring-dispatcher, we have added view resolver and component scan attribute to scan application controller

<?xml version=“1.0” encoding=“UTF-8”?>

<beans xmlns=“http://www.springframework.org/schema/beans”

xmlns:context=“http://www.springframework.org/schema/context”

xmlns:mvc=“http://www.springframework.org/schema/mvc”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xmlns:util=“http://www.springframework.org/schema/util”

xsi:schemaLocation=

            http://www.springframework.org/schema/mvc

            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 

            http://www.springframework.org/schema/beans      

            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 

            http://www.springframework.org/schema/context  

            http://www.springframework.org/schema/context/spring-context-3.0.xsd

            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd”>

<context:annotation-config />

<context:component-scan base-package=“com.helical.scrunch.controller” />

<bean class=“org.springframework.web.servlet.view.InternalResourceViewResolver”>

<property name=“prefix”>

<value>/WEB-INF/jsp/</value>

</property>

<property name=“suffix”>

<value>.jsp</value>

</property>

</bean>

</beans>

\src\main\webapp\WEB-INF\spring-security.xml

This is called spring-security configuration file to specify login details and security url’s to check for login.

<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.2.xsd”>

 

<!– enable use-expressions –>

<http auto-config=“true” use-expressions=“true”>

<intercept-url pattern=“/admin**” access=“ROLE_ADMIN” />

</http>

 

<authentication-manager>

<authentication-provider>

<user-service>

<user name=”test” password=”test” authorities=”ROLE_ADMIN”>

<password-encoder hash=“bcrypt” />

</user-service>

</authentication-provider>

</authentication-manager>

</beans:beans>


\src\main\java\com\helical\scrunch\controller\MainController.java

package com.helical.scrunch.controller;

@Controller

public class MainController {

@RequestMapping(value = “/admin**”, method = RequestMethod.GET)

public ModelAndView adminPage() {

ModelAndView model = new ModelAndView();

model.addObject(“title”, “Redirected to Admin Page”);

model.addObject(“message”, “This page is for ROLE_ADMIN only!”);

model.setViewName(“admin”);

return model;

}

}

Here is admin.jsp page which will display after successful login

\src\main\webapp\WEB-INF\jsp\admin.jsp

<%@taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core”%>

<%@page session=“true”%>

<html>

<body>

<h1>Title : ${title}</h1>

<h1>Message : ${message}</h1>

</html>

</body>

Spring provides the build in login page for us or you can develop your own custom login page.

If everything is correct you can see the login page on http://localhost:8080/your-project-name/admin