Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects

Wednesday, 28 May 2014

Spring Security Authentication and Authorization Example with Database Credentials

In our previous discussions we go through 'What is Spring Security' and 'Custom login form in Spring Security', previously we have used XML based username and password to authenticate a user. In this particular blog we will see how to use username, password and role details from database to authenticate a user. At the end of the blog we will see how to perform authorization with spring security based on different roles.

Project Structure

Let us start our discussion with project structure, please go through the pom.xml file to get information regarding dependencies needed in spring-security. Setup a Simple Maven project and import it in Eclipse, and follow the step by step instructions mentioned below.

Database setup

As per spring security documentation, we need to create two suggested tables 'users' and 'user_roles' in database with exact datatypes and columns. Here is the script to create tables in DB.
-- Dumping database structure for spring_security
CREATE DATABASE IF NOT EXISTS `spring_security` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `spring_security`;

-- Dumping structure for table spring_security.users
  `username` varchar(45) NOT NULL,
  `password` varchar(450) NOT NULL,
  `enabled` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`username`)

-- Dumping structure for table spring_security.user_roles
  `user_role_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(45) NOT NULL,
  `ROLE` varchar(45) NOT NULL,
  PRIMARY KEY (`user_role_id`),
  UNIQUE KEY `uni_username_role` (`ROLE`,`username`),
  KEY `fk_username_idx` (`username`),
  CONSTRAINT `fk_username` FOREIGN KEY (`username`) REFERENCES `users` (`username`)

Let us now add two users 'andrew' and 'robert' and their roles to the database, 'andrew' have two roles 'ROLE_USER' and 'ROLE_ADMIN' and 'robert' have only one role 'ROLE_USER'. See the script below:
INSERT INTO `users` (`username`, `password`, `enabled`) VALUES
 ('andrew', 'andrew@123', 1),
 ('robert', 'robert@123', 1);

INSERT INTO `user_roles` (`user_role_id`, `username`, `ROLE`) VALUES
 (2, 'andrew', 'ROLE_ADMIN'),
 (1, 'andrew', 'ROLE_USER'),
 (3, 'robert', 'ROLE_USER');

Dependencies required for spring-security - pom.xml

Here is a list of all required dependencies that we need to add in pom.xml, to get spring security basic features all we need to do is to add 'spring-security-web' and 'spring-security-config' to pom.xml file.
<project xmlns="" xmlns:xsi=""
 <name>SpringSecurityDemo Maven Webapp</name>

   <id>Nagesh Chauhan</id>
    <role>Java Developer</role>


   <!-- Maven compiler plugin -->







The very first thing we need to do is adding following filters to our web.xml. These filters tells the container that all upcoming requests will be handled by spring security for security purpose. DelegatingFilterProxy is a class present in spring-security jars which delegates control to a filter chaining defined in spring-security internals. Note that we have given the bean name as ‘springSecurityFilterChain’ one should not change the name of this bean as this is being configured by spring-security internal infrastructure. By adding these filters to web.xml now we are ready to configure security in the application.
<web-app xmlns="" xmlns:xsi=""

 <display-name>Sample Spring Maven Project</display-name>







< br/>


This is a simple spring configuration file with a view resolver bean to show jsp's and two useful annotation information regarding component-scan and annotation-driven.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 xmlns:xsi="" xmlns:context=""
 xmlns:util="" xmlns:mvc=""

 <context:component-scan base-package="com.beingjavaguys.controller" />
 <mvc:annotation-driven />

<bean id="dataSource"
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/spring_security" />
  <property name="username" value="root" />
  <property name="password" value="root" />

  <property name="prefix">
  <property name="suffix">


By adding filter to web.xml we are now able to configure security in our application, we can start with minimal http configuration for incoming requests. This tells that all upcoming requests which are matching to the pattern given in ‘pattern’ attribute will be secured bu spring-security and these requests will need ‘ROLE_USER’ role to access them. Here the thing to be noted is that ‘ROLE_’ prefix is a marker to define roles, ‘access’ attribute can accept a number of roles separated by a comma. Regarding ‘’ we can have a number of different entries for different url’s, these entries will be evaluated in the order they are defined here. The very first match to the incoming request will be executed. We can also add a method attribute to limit the match to a particular HTTP method (GET, POST, PUT etc.).
<beans:beans xmlns=""
 xmlns:beans="" xmlns:xsi=""

 <http auto-config="true">
  <access-denied-handler error-page="/403page" />
  <intercept-url pattern="/user**" access="ROLE_USER" />
  <intercept-url pattern="/admin**" access="ROLE_ADMIN" />
  <form-login login-page='/login' username-parameter="username"
   password-parameter="password" default-target-url="/user"
   authentication-failure-url="/login?authfailed" />
  <logout logout-success-url="/login?logout" />

 <!-- <authentication-manager> <authentication-provider> <user-service> <user 
  name="user" password="user@123" authorities="ROLE_ADMIN" /> </user-service> 
  </authentication-provider> </authentication-manager> -->

   <jdbc-user-service data-source-ref="dataSource"
    users-by-username-query="select username,password, enabled from users where username=?"
    authorities-by-username-query="select username, role from user_roles where username =?  " />



This is a simple Controller class with few request mappings in it, we have '/login' to redirect the user to login form along with custom messages if required. Another mapping id for admin page '/admin' and '/user' only logged in users with required 'USER_ROLES' will be able to see the pages.
package com.beingjavaguys.controller;

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

public class LoginController {

 public ModelAndView getLoginForm(
   @RequestParam(required = false) String authfailed, String logout,
   String denied) {
  String message = "";
  if (authfailed != null) {
   message = "Invalid username of password, try again !";
  } else if (logout != null) {
   message = "Logged Out successfully, login again to continue !";
  } else if (denied != null) {
   message = "Access denied for this user !";
  return new ModelAndView("login", "message", message);

 public String geUserPage() {
  return "user";

 public String geAdminPage() {
  return "admin";

 public String ge403denied() {
  return "redirect:login?denied";



This is actual custom login form that will be rendered to the user to add credentials and log in to the application. In this file all we need to do is adding spring specific action 'j_spring_security_check' so that spring-security can intercept it and can authentication done.
<%@taglib prefix="c" uri=""%>
<title>Login Form |</title>
  <br /> <br /> <br />
  <h2>Login Here</h2>
  <br />
  <div style="text-align: center; padding: 30px;border: 1px solid green;width: 250px;">
   <form method="post" action="<c:url value='j_spring_security_check' />">

      <td colspan="2" style="color: red">${message}</td>

      <td>User Name:</td>
      <td><input type="text" name="username" />
      <td><input type="password" name="password" />
      <td> </td>
      <td><input type="submit" value="Login" />



This is another simple jsp file, this will be rendered to the browser if the user with 'ROLE_ADMIN' is logged in successfully. We have also added a logout link in the page, logout functionality to work onw has to make the spring specific link '/j_spring_security_logout'. By clicking the link spring-security will logged out the current logged in used.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<%@taglib prefix="c" uri=""%>
<title>Admin Page |</title>
<c:url value="/j_spring_security_logout" var="logoutUrl" />
  <br /> <br /> <br />
  <h2>Admin | You are now logged in</h2>
  <h3><a href="${logoutUrl}">Logout</a></h3>


This is another simple jsp file, this will be rendered to the browser if the user with 'ROLE_USER' role is logged in successfully. We have also added a logout link in the page, logout functionality to work onw has to make the spring specific link '/j_spring_security_logout'. By clicking the link spring-security will logged out the current logged in used.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<%@taglib prefix="c" uri=""%>
<title>User Page |</title>
<c:url value="/j_spring_security_logout" var="logoutUrl" />
  <br /> <br /> <br />
  <h2>User | You are now logged in</h2>
  <h3><a href="${logoutUrl}">Logout</a></h3>

Here we are done with all required configurations, if everything goes right you will see below mentioned screens in your browser.

Authorization with spring security

Authentication means who can enter in the system based on their login credentials, whereas authorization tells the system that what are the authenticated users those can access a particular system functionality.

Trying to aceess '/admin' page, hit url "http://localhost:8080/SpringSecurityDemo/admin"
Spring security will redirect it to login page, because according to the interceptor configuration only a logged in user can view this page and that too having user role as 'ROLE_ADMIN'.

Lets try to login with 'robert' we know that 'robert' does not have 'USER_ADMIN' role, so there will be a '403' access denied error, this is what we called 'Authorization in Spring security'. Although 'robert' has valid login-password but cant view the url's whose role it does not have.

Now let us try to login again with 'andrew' credential, 'andrew' has required role i.e.'ROLE_ADMIN' to view '/admin' page so this will be a successful login and will be redirected to admin page.

We know that both users have 'ROLE_USER', if you try to access 'http://localhost:8080/SpringSecurityDemo/user' then it will be success login and you will see user page.

This is all about ' Spring Security Authentication and Authorization Example with Database Credentials'. In upcoming blogs we will see more about Spring, Hibernate, Java and Other opensource technologies.

Thanks for reading !
Being Java Guys Team

Download "Spring Security Custom Login Form Example Project" from "SkyDrive"


  1. Wrong project link given to download it does not contain database code
    please upload the right project and inform me(

  2. This comment has been removed by the author.

  3. can we add additional fields to database table "user"

  4. Good try..but after logout it direct by default to user login page....and admin can not login after logout.....

  5. if some one could fix issue in this example Issue is if you give correct login ID & pwd for USER_ROLE from admin login it will give you are not authorized that is fine but at the same time if you hit user URL it will directly take you to user.jsp without any login page in between

  6. I am getting error as

    DEBUG o.s.s.a.d.DaoAuthenticationProvider - Authentication failed: password does not match stored value

    15:44:29.782 [http-nio-8080-exec-8] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Authentication request failed: Bad credentials

  7. Hello! I had deployment error: "Error during artifact deployment".
    Tomcal localhost log wrote this: " org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'loginController' bean method

    Can you help me, please?

  8. Great tutorial! Thank you!

  9. very much understandable blog thank you


Like Us on Facebook

Like Us On Google+


Skype: neel4soft