Showing posts with label Spring Security. Show all posts
Showing posts with label Spring Security. Show all posts

Wednesday, 8 January 2014

Spring Security: Remember me Example

Remember me authentication is a mechanism that allows a user to maintain his identity across multiple browser sessions. Typically, a browser session ends when we close the browser. This means that with Remember-me, a user will be able to automatically login even after he restarts the browser. It remembers the identity of the user between two different sessions.

This is typically accomplished by sending a cookie to the browser, with the cookie being detected during future sessions and causing automated login to take place. Spring Security provides the necessary hooks for these operations to take place, and has two concrete remember-me implementations.  One uses hashing to preserve the security of cookie-based tokens and the other uses a database or other persistent storage mechanism to store the generated tokens. Note that both the implementations require a UserDetailsService. 

1. Simple Hash-Based Token Approach

This approach uses hashing to achieve a useful remember-me strategy. In essence a cookie is sent to the browser upon successful interactive authentication, with the cookie being composed as follows:

base64(username + ":" + expirationTime + ":" + 
md5Hex(username + ":" + expirationTime + ":" password + ":" + key)) 

username: As identifiable to the `UserDetailsService`. 

password: That matches the one in the retrieve UserDetails. 

expirationTime: The date and time when the remember-me token expires, expressed in milliseconds .

key: A private key to prevent modification of the remember-me token.

The remember-me token is valid only for the period specified, and provided that the username, password and key does not change. To enable remember-me authentication just add the <remember-me> element into <http element>

<http> ... <remember-me key="myAppKey"/> </http>


2. Persistent Token Approach

This approach uses the database to store the generated tokens. The database that will be used should contain a persistent_logins table, created using the following SQL (or equivalent):

create table persistent_logins (username varchar(64) not null, series varchar(64) primary key, token varchar(64) not null, last_used timestamp not null)

To use this approach with the namespace configuration, you need to supply a datasource reference

<http> ... <remember-me data-source-ref="someDataSource"/> </http>

Example

The setup is the same as the one used for my previous post demonstrating the use of a custom UserDetailsService.

Only changes required are in spring-security.xml configuration. We will be using the Hash-Based token approach. 



 
  

  
  

  

  
 

 
  
 

Demo

If we try to access the URL- '/SpringSecurity/user/welcome'
Spring Security intercepts this URL and presents a login form.

Note that there exists a check-box for remember me.If we tick this check-box and login with valid credentials, a cookie named 'SPRING_SECURITY_REMEMBER_ME' is created along with the cookie storing JSessionId. 




If we delete this cookie for JSessionId, we are still able to login automatically and access the intercepted URL.

This is all because of the simple Hash-Based generated token stored inside the browser's cookie.

You can view/download the complete source code from here.

Spring Security: Using a custom Authentication Provider and a Password Encoder

To get familiar with Spring Security basic concepts you can refer to my previous posts. In this post, we will see how we can use a custom authentication provider to perform the authentication.

The most common approach to verifying an authentication request is to load the corresponding UserDetails and check the loaded password against the one that has been entered by the user. This is the approach used by the 
DaoAuthenticationProvider. It is the simplest AuthenticationProvider implemented by Spring Security.It leverages a UserDetailsService (as a DAO) in order to lookup the username, password and GrantedAuthorities. It authenticates the user simply by comparing the password submitted in a UsernamePasswordAuthenticationToken against the one loaded by the UserDetailsService.

web.xml contents remain the same as given in my previous post for using a custom UserDetailsService.Following are the dependencies for this example.

pom.xml


 4.0.0
 SpringSecurity
 SpringSecurity
 war
 0.0.1-SNAPSHOT
 SpringSecurity1 Maven Webapp
 http://maven.apache.org
 
  
   junit
   junit
   3.8.1
   test
  
  
   org.springframework
   spring-orm
   3.2.0.RELEASE
  
  
   org.springframework
   spring-webmvc
   3.2.0.RELEASE
  
  
   org.springframework.security
   spring-security-web
   3.2.0.RELEASE
  
  
   org.springframework.security
   spring-security-config
   3.2.0.RELEASE
  
  
   org.springframework.security
   spring-security-taglibs
   3.2.0.RELEASE
  
  
   jstl
   jstl
   1.2
   compile
  
  
   taglibs
   standard
   1.1.2
   compile
  
  
   javax
   javaee-api
   7.0
  
  
   org.hibernate
   hibernate-core
   3.6.10.Final
  
  
   mysql
   mysql-connector-java
   5.1.26
  
  
   commons-dbcp
   commons-dbcp
   20030825.184428
  
  
   commons-pool
   commons-pool
   20030825.183949
  
  
   commons-collections
   commons-collections
   3.2.1
  
  
   javassist
   javassist
   3.12.1.GA
  
  
   org.codehaus.jackson
   jackson-mapper-asl
   1.9.12
  
 
 
  SpringSecurity
 

spring-security.xml



 
  
  
   
  
 

 
  
  
 

 
  
  
 

 

 


This is how you can configure an authentication provider. 'authService' bean is the class which implements the UserDetailsService interface. It is the same as given in the previous post. The PasswordEncoder is optional. A PasswordEncoder provides encoding and decoding of passwords presented in the UserDetailsobject that is returned from the configured UserDetailsService.

Spring Security’s PasswordEncoder interface is used to support the use of passwords which are encoded in some way in persistent storage. You should never store passwords in plain text. Always use a one-way password hashing algorithm such as bcrypt which uses a built-in salt value which is different for each stored password. Do not use a plain hash function such as MD5 or SHA, or even a salted version. Bcrypt is deliberately designed to be slow and to hinder offline password cracking, whereas standard hash algorithms are fast and can easily be used to test thousands of passwords in parallel on custom hardware. You might think this doesn’t apply to you since your password database is secure and offline attacks aren’t a risk. If so, do some research and read up on all the high-profile sites which have been compromised in this way and have been pilloried for storing their passwords insecurely. It’s best to be on the safe side. 

Using 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' is a good choice for security. Note that for the authentication provider to be able to compare password submitted in a UsernamePasswordAuthenticationToken against the one loaded by the UserDetailsService, you will need to store these passwords inside some database only after encrypting it using the BCryptPasswordEncoder.

spring-servlet.xml





 

 

 
  
   
    
   
  
 

 
  
  
 

 
  
  
  
  
 

 
  
  
   classpath:hibernate.cfg.xml
  
  
   org.hibernate.cfg.AnnotationConfiguration
   
  
 

 

 
  
 

Controller

package com.spring.security.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring.security.domain.MyUser;
import com.spring.security.service.IUserService;

@Controller
public class HelloController {

 @Autowired
 IUserService userService;

 @RequestMapping(value = "/user/welcome", method = RequestMethod.GET)
 public String printWelcomeUser() {
  return "hello";
 }

 @RequestMapping(value = "/admin/welcome", method = RequestMethod.GET)
 public String printWelcomeAdmin() {
  return "admin";
 }

 @RequestMapping(value = "/login", method = RequestMethod.GET)
 public String getLoginPage(Model model) {
  return "login";
 }

 @RequestMapping(value = "/home", method = RequestMethod.GET)
 public String getHomePage(Model model) {
  return "hello";
 }

 @RequestMapping(value = "/accessdenied", method = RequestMethod.GET)
 public String getFailurePage(Model model) {
  return "failure";
 }

 @RequestMapping(value = "/logout", method = RequestMethod.GET)
 public String getLogoutPage(Model model, HttpServletRequest req) {
  req.getSession().invalidate();
  return "logout";
 }

 @RequestMapping(value = "/user", method = RequestMethod.POST)
 @ResponseBody
 String saveUser(@RequestBody MyUser user, HttpServletResponse response) {
  System.out.println("User:" + user.getUsername());
  userService.saveUser(user);
  response.setStatus(201);
  return "success";
 }
}

AuthService

package com.spring.security.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.security.dao.IUserDao;
import com.spring.security.domain.MyUser;
import com.spring.security.service.IAuthService;

@Service
public class AuthServiceImpl implements IAuthService, UserDetailsService {

 @Autowired
 IUserDao userDao;

 @Transactional
 @Override
 public UserDetails loadUserByUsername(String username)
   throws UsernameNotFoundException {

  MyUser details = userDao.getUser(username);
  Collection authorities = new ArrayList();
  SimpleGrantedAuthority userAuthority = new SimpleGrantedAuthority(
    "ROLE_USER");
  SimpleGrantedAuthority adminAuthority = new SimpleGrantedAuthority(
    "ROLE_ADMIN");
  if (details.getRole().equals("user"))
   authorities.add(userAuthority);
  else if (details.getRole().equals("admin")) {
   authorities.add(userAuthority);
   authorities.add(adminAuthority);
  }
  UserDetails user = new User(details.getUsername(),
    details.getPassword(), true, true, true, true, authorities);
  return user;
 }

}

UserSevice

package com.spring.security.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.security.dao.IUserDao;
import com.spring.security.domain.MyUser;
import com.spring.security.service.IUserService;

@Service
public class UserServiceImpl implements IUserService {

 @Autowired
 IUserDao userDao;

 @Autowired
 private BCryptPasswordEncoder passwordEncoder;

 @Transactional
 @Override
 public void saveUser(MyUser user) {
  String password = user.getPassword();
  String encryptedPassword = passwordEncoder.encode(password);
  user.setPassword(encryptedPassword);
  userDao.saveUser(user);
 }

}
As seen above, the password is first encrypted and then passed to the userDao to get saved.


UserDao

package com.spring.security.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.spring.security.dao.IUserDao;
import com.spring.security.domain.MyUser;

@Repository
public class UserDaoImpl implements IUserDao {

 @Autowired
 private SessionFactory sessionFactory;

 @Override
 public MyUser getUser(String username) {
  Session session = sessionFactory.getCurrentSession();
  Criteria criteria = session.createCriteria(MyUser.class);
  criteria.add(Restrictions.eq("username", username));
  MyUser user = (MyUser) criteria.uniqueResult();
  return user;
 }

 @Override
 public void saveUser(MyUser user) {
  sessionFactory.getCurrentSession().save(user);
 }
}

You can view/download the complete source code from here.

Thanks !

Monday, 30 December 2013

Spring Security: Custom UserDetails Service and Login form

To get familiar with key concepts of Spring Security, refer to my previous post. In this post, we will be writing a custom UserDetails service which will talk to the database [hibernate + MySQL] and fetch the user authentication information.

Setup

This is how my project structure looks like:

Dependencies

If you are using maven, following is the pom.xml file containing the list of all the dependencies:

 4.0.0
 SpringSecurity
 SpringSecurity1
 war
 0.0.1-SNAPSHOT
 SpringSecurity1 Maven Webapp
 http://maven.apache.org
 
  
   junit
   junit
   3.8.1
   test
  
  
   org.springframework
   spring-orm
   3.2.0.RELEASE
  
  
   org.springframework
   spring-webmvc
   3.2.0.RELEASE
  
  
   org.springframework.security
   spring-security-web
   3.2.0.RELEASE
  
  
   org.springframework.security
   spring-security-config
   3.2.0.RELEASE
  
  
   org.springframework.security
   spring-security-taglibs
   3.2.0.RELEASE
  
  
   jstl
   jstl
   1.2
   compile
  
  
   taglibs
   standard
   1.1.2
   compile
  
  
   javax
   javaee-api
   7.0
  
  
   org.hibernate
   hibernate-core
   3.6.10.Final
  
  
   mysql
   mysql-connector-java
   5.1.26
  
  
   commons-dbcp
   commons-dbcp
   20030825.184428
  
  
   commons-pool
   commons-pool
   20030825.183949
  
  
   commons-collections
   commons-collections
   3.2.1
  
  
   javassist
   javassist
   3.12.1.GA
  
  
   org.codehaus.jackson
   jackson-mapper-asl
   1.9.12
  
 
 
  SpringSecurity1
 



Configuring web.xml


  SpringSecurity1
  
    /WEB-INF/jsp/index.jsp
  
  
    spring
    
            org.springframework.web.servlet.DispatcherServlet
        
    1
  
  
    spring
    /
  
  
    
                  org.springframework.web.context.ContextLoaderListener
                
  
  
    contextConfigLocation
    
   /WEB-INF/spring-servlet.xml,
   /WEB-INF/spring-security.xml
  
  
  
    springSecurityFilterChain
    
                  org.springframework.web.filter.DelegatingFilterProxy
                
  
  
    springSecurityFilterChain
    /*
  

This provides a hook into the Spring Security web infrastructure. DelegatingFilterProxy is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security. Note that you should not use this bean name yourself. Once you’ve added this to your web.xml, you’re ready to start editing your application context file. Web security services are configured using the <http> element.

Configuring spring-security.xml



 
  
  
   
  
 

 
  
  
 


The <intercept-url> element defines a pattern which is matched against the URLs of incoming requests using an ant path style syntax. In general the xml states that we want to log in to the application using a form with username and password, and that we want a logout URL registered which will allow us to log out of the application.The access attribute defines the access requirements for requests matching the given pattern. With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request.Here, it states that we want all URLs matching the pattern '/user/**' to be secured, requiring the role ROLE_USER to access them.Similarly, we want all URls matching the pattern '/admin/**' require the role ROLE_ADMIN to access them.

If a form login isn't prompted by an attempt to access a protected resource, the default-target-url option comes into play. This is the URL the user will be taken to after successfully logging in, and defaults to "/". One can also configure things so that the user always ends up at this page (regardless of whether the login was "on-demand" or they explicitly chose to log in) by setting the always-use-default-target attribute to "true". The authentication-failure-attribute defines the URL that  shows the custom access denied page if the user fails to authenticate himself.

The logout-success-url specifies the URL which will be presented to the user once the user has logged out.

Authentication manager will handle all the authentication requests. All authentication-provider elements must be children of the <authentication-manager> element, which creates a ProviderManager and registers the authentication providers with it. The user-service-ref attribute for the authentication provider says that we have a custom implementation of Spring Security’s UserDetailsService, called "authService" defined in the application context file. UserDetailsService is a special interface which has the only method which accepts a String-based username argument and returns a UserDetails.

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;


UserDetails is a core interface in Spring Security which represents a principal, but in an extensible and application-specific way. Think of UserDetails as the adapter between your own user database and what Spring Security needs inside the SecurityContextHolder. The returned UserDetails is an interface that provides getters that guarantee non-null provision of authentication information such as the username, password, granted authorities and whether the user account is enabled or disabled.

Note that UserDetailsService is purely a DAO for user data and performs no other function other than to supply that data to other components within the framework. In particular, it does not authenticate the user, which is done by the AuthenticationManager.

Configuring spring-servlet.xml




 

 

 
  
   
    
   
  
 

 
  
  
 

 
  
  
  
  
 

 
  
  
   classpath:hibernate.cfg.xml
  
  
   org.hibernate.cfg.AnnotationConfiguration
   
  
 

 

 

 
  
 

Here, we have defined a bean authService which implements the interface UserDetailsService. It also has hibernate configurations as we will be storing the user authentication information in my database [MySQL]. 

hibernate.cfg.xml contents


 
  
  
  1

  
  org.hibernate.dialect.MySQLDialect

  
  org.hibernate.cache.NoCacheProvider

  
  true

  create
  
  
  
 

MyUser model object

package com.spring.security.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "userdetails")
public class MyUser {

 @Id
 @GeneratedValue
 private int userId;
 private String username;
 private String password;
 private String role;

 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 int getUserId() {
  return userId;
 }

 public void setUserId(int userId) {
  this.userId = userId;
 }

 public String getRole() {
  return role;
 }

 public void setRole(String role) {
  this.role = role;
 }

}
It has username, password and roles attributes which will be stored in database.

UserDetailsService Implementation

package com.spring.security.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.security.dao.IUserDao;
import com.spring.security.domain.MyUser;
import com.spring.security.service.IAuthService;

@Service
public class AuthServiceImpl implements IAuthService, UserDetailsService {

 @Autowired
 IUserDao userDao;

 @Transactional
 @Override
 public UserDetails loadUserByUsername(String username)
   throws UsernameNotFoundException {

  MyUser details = userDao.getUser(username);
  Collection authorities = new ArrayList();
  SimpleGrantedAuthority userAuthority = new SimpleGrantedAuthority(
    "ROLE_USER");
  SimpleGrantedAuthority adminAuthority = new SimpleGrantedAuthority(
    "ROLE_ADMIN");
  if (details.getRole().equals("user"))
   authorities.add(userAuthority);
  else if (details.getRole().equals("admin")) {
   authorities.add(userAuthority);
   authorities.add(adminAuthority);
  }
  UserDetails user = new User(details.getUsername(),
    details.getPassword(), true, true, true, true, authorities);
  return user;
 }
}

As u can see, AuthServiceImpl implements UserDetailsService interface. This needs to override a loadUserByUsername() method that takes username as an argument and returns a UserDetails object. We fetch a MyUser object from DB that stores the username,password and role for a user. It checks if role present is 'user' it adds a ROLE_USER authority to the authorities list. If it is 'admin' it adds ROLE_ADMIN as well as ROLE_USER authorities. It then creates a UserDetails object using a constructor passing the appropriate arguments.

Controller

package com.spring.security.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring.security.domain.MyUser;
import com.spring.security.service.IUserService;

@Controller
public class HelloController {

 @Autowired
 IUserService userService;

 @RequestMapping(value = "/user/welcome", method = RequestMethod.GET)
 public String printWelcomeUser() {
  return "hello";
 }

 @RequestMapping(value = "/admin/welcome", method = RequestMethod.GET)
 public String printWelcomeAdmin() {
  return "admin";
 }

 @RequestMapping(value = "/login", method = RequestMethod.GET)
 public String getLoginPage(Model model) {
  return "login";
 }

 @RequestMapping(value = "/home", method = RequestMethod.GET)
 public String getHomePage(Model model) {
  return "hello";
 }

 @RequestMapping(value = "/accessdenied", method = RequestMethod.GET)
 public String getFailurePage(Model model) {
  return "failure";
 }

 @RequestMapping(value = "/logout", method = RequestMethod.GET)
 public String getLogoutPage(Model model, HttpServletRequest req) {
  req.getSession().invalidate();
  return "logout";
 }

 @RequestMapping(value = "/user", method = RequestMethod.POST)
 @ResponseBody
 String saveUser(@RequestBody MyUser user, HttpServletResponse response) {
  System.out.println("User:" + user.getUsername());
  userService.saveUser(user);
  response.setStatus(201);
  return "success";
 }
}

UserDao

package com.spring.security.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.spring.security.dao.IUserDao;
import com.spring.security.domain.MyUser;

@Repository
public class UserDaoImpl implements IUserDao {

 @Autowired
 private SessionFactory sessionFactory;

 @Override
 public MyUser getUser(String username) {
  Session session = sessionFactory.getCurrentSession();
  Criteria criteria = session.createCriteria(MyUser.class);
  criteria.add(Restrictions.eq("username", username));
  MyUser user = (MyUser) criteria.uniqueResult();
  return user;
 }

 @Override
 public void saveUser(MyUser user) {
  sessionFactory.getCurrentSession().save(user);
 }
}


Views

admin.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




Hello admin


Welcome admin !

Logout
Simple welcome page that displays Welcome Admin !The default logout URL is /j_spring_security_logout, but you can set it to something else using the logout-url attribute in spring-security.xml.

hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>




Hello user



 

Welcome User !

Logout
Simple welcome page that displays Welcome User !

index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>





Insert title here



 

Hello All

Home page

login.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>



 

Login to Spring Security App

Username:
Password:
 
 
Post request to  /j_spring_security_check authenticates the user. The username parameter is set to j_username and password to j_password. 

logout.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>




Logout


 

You have been successfully logged out !

Go back to login page
Logout page to which a user is directed after successful log out.

failure.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>




 

Unauthenticated user !!

Access denied! Go back to login page
Access denied page which is shown to the user if he fails to authenticate.


Demo

This is my database state.



When we try to access /user/welcome resource, we will be prompted with our custom login page.




When we log in as user1, we will be granted ROLE_USER authority and hence we will not be able to access /admin/welcome which requires ROLE_ADMIN authority.



If we enter incorrect credentials, we will be presented with our custom access denied web page. 



You can view/download the complete source code from here.

Thanks !!

Friday, 27 December 2013

Spring Security : User Details in properties file

In my previous post, a simple example demonstrating Spring Security was presented wherein the user details were provided int the spring-security.xml file. 

In this example, the user details will be stored in an external properties file. Rest of the configuration remains the same. The properties file should look like this -

username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]

Sample properties file
user1=user1password,ROLE_USER,ROLE_ADMIN,enabled
user2=user2password,ROLE_USER,enabled

Configuring spring-servlet.xml



 
  
  
  
  
 

 
  
   
  
 

Notice that in this case we provide users.properties as a value for the attribute 'properties' for the user-service.

You can download the complete source code for this example from here.

Spring Security Introduction : Basic Authentication Example

Introduction

Spring Security is a major module in Spring Distribution. It is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements.

Before going forward lets have an overview of some of the key concepts:

  • Web/HTTP Security - It is the most complex part.It sets up the filters and related service beans used to apply the framework authentication mechanisms, to secure URLs, to render login and error pages and much more.
  • Business Object (Method) Security - It provides options for securing the service layer.
  • AuthenticationManager - It handles authentication requests from other parts of the framework.
  • AccessDecisionManager - It provides access decisions for web and method security. A default one will be registered, but you can also choose to use a custom one, declared using normal Spring bean syntax.
  • AuthenticationProviders - They provide mechanisms against which the authentication manager authenticates users. The namespace provides support for several standard options and also a means of adding custom beans declared using a traditional syntax.
  • UserDetailsService - It is closely related to authentication providers, but often also required by other beans.It is used to provide authentication information.
In this example, the user authentication information is maintained in xml configuration file for spring security.


Setup

This is how the final project structure looks like -



Dependencies

If you are using maven, following are the dependencies which will be required -

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>

These are the minimal set of dependencies for Spring Security. Using additional features will require addition of appropriate project modules.

Configuring web.xml



    SpringSecurity1
    
        /WEB-INF/jsp/index.jsp
    
 
    
        spring
        
            org.springframework.web.servlet.DispatcherServlet
        
        1
    
    
        spring
        /
     
    
    
  
                  org.springframework.web.context.ContextLoaderListener
                
 
 
 
  contextConfigLocation
  
   /WEB-INF/spring-servlet.xml,
   /WEB-INF/spring-security.xml
  
 
 
 
 
  springSecurityFilterChain
  
                  org.springframework.web.filter.DelegatingFilterProxy
                
 
 
 
  springSecurityFilterChain
  /*
 
This provides a hook into the Spring Security web infrastructure. DelegatingFilterProxy is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security. Note that you should not use this bean name yourself. Once you’ve added this to your web.xml, you’re ready to start editing your application context file. Web security services are configured using the <http> element.

Don't forget to include spring-security.xml file for the Context Configuration location.

Configuration : spring-security.xml




 
  
  
  
  
 

 
  
   
    
   
  
 



This is the configuration file where we provide all the spring security configurations. <http> element is the parent for all web-related namespace functionality. The <intercept-url> element defines a patternwhich is matched against the URLs of incoming requests using an ant path style syntax. All the URLs beginning with welcome will be intercepted in this case. It says that we want all URLs matching the pattern '/welcome**' to be secured, requiring the role ROLE_USER to access them, we want to log in to the application using a form with username and password, and that we want a logout URL registered which will allow us to log out of the application.
The access attribute defines the access requirements for requests matching the given pattern. With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request.The logout-success-url specifies the URL which will be presented to the user once the user has logged out.

If a form login isn’t prompted by an attempt to access a protected resource, the default-target-url option comes into play. This is the URL the user will be taken to after successfully logging in, and defaults to "/". One can also configure things so that the user always ends up at this page (regardless of whether the login was "on-demand" or they explicitly chose to log in) by setting the always-use-default-targetattribute to "true".


The <authentication-provider> element creates a DaoAuthenticationProvider bean and the <user-service> element creates an InMemoryDaoImpl. All authentication-provider elements must be children of the <authentication-manager> element, which creates a ProviderManager and registers the authentication providers with it.

The configuration above defines two users, their passwords and their roles within the application (which will be used for access control). When a user enters login information, his username and password are matched with those specified in user-service. If successfully authenticated, the mentioned attributes are linked to the user. These attributes decide whether a user is authorized to make certain requests or not.

Setting up the Controller and spring-servlet.xml 

This is my controller.
package com.spring.security;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {

 @RequestMapping(value = "/welcome", method = RequestMethod.GET)
 public String printWelcome(Model model) {
  model.addAttribute("message", "Spring Security says Hello !");
  return "hello";
 }

 @RequestMapping(value = "/login", method = RequestMethod.GET)
 public String getLoginPage(Model model) {
  return "login";
 }

 @RequestMapping(value = "/home", method = RequestMethod.GET)
 public String getHomePage(Model model) {
  return "index";
 }

 @RequestMapping(value = "/logout", method = RequestMethod.GET)
 public String getLogoutPage(Model model, HttpServletRequest req) {
  req.getSession().invalidate();
  return "logout";
 }
}

spring-servlet.xml



 

 

 
  
  
 


Views

hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>




Insert title here



 

Message : ${message}

Logout
The default logout URL is /j_spring_security_logout, but you can set it to something else using the logout-url attribute.

logout.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>




Logout


 

You have been successfully logged out !

Go back to login page
The URL where you will find the security login page is '/spring_security_login'.

index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>





Home



 

Home Page

This is a simple home page


Demo

When you try to access '/SpringSecurity1/welcome' you will be prompted with a Spring Security login page. You might be wondering where the login form came from when you were prompted to log in, since we made no mention of any HTML files or JSPs. In fact, since we didn’t explicitly set a URL for the login page, Spring Security generates one automatically, based on the features that are enabled and using standard values for the URL which processes the submitted login, the default target URL the user will be sent to after logging in and so on.






With correct credentials you will be forwarded to the welcome page



An unsuccessful login will result in a Bad Credentials page.

This was a simple example to give you an overview on Spring Security. In my upcoming posts we will be looking into details many other features provided by Spring Security. You can download the source code of this example from here. 

Thanks and Happy coding !