Custom UserDetailsService example for spring 3 security

So far we have learned about http basic authentication, jdbc user service and xml based user service configuration examples for securing your web applications using spring security. Lets move forward in the series. In this post, I will e giving the example code for configuring custom user details service implementation and way to use it in your application.

UserDetailsService interface is used in order to lookup the username, password and GrantedAuthorities for any given user. This interface provide only one method which implementing class need to implement.

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

Here UserDetails is container for core user information. According to docs, its implementations are not used directly by Spring Security for security purposes. They simply store user information which is later encapsulated into Authentication objects. This allows non-security related user information (such as email addresses, telephone numbers etc) to be stored in a convenient location. A very good sample implementation can be like User class.

In our case i.e. for custom user detail service usage, AuthenticationProvider authenticates the user simply by
comparing the password submitted in a UsernamePasswordAuthenticationToken against the one loaded by
the UserDetailsService.

Example implementation

I have taking forward the code base as written in Spring 3 hibernate integration example and modified in spring 3 xml based security demo. In the application-security.xml file, I will update the configuration to use Employee dao as custom user detail service.

<!-- Defined in employee-servlet.xml -->
<bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDaoImpl"></bean>

<!-- Configured in application-security.xml-->
<authentication-manager alias="authenticationManager">
	<authentication-provider user-service-ref="employeeDAO"></authentication-provider>

Complete application-security.xml file will look like this:

< ?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns=""

	<http auto-config="true"  use-expressions="true">
		<intercept-url pattern="/login" access="permitAll"></intercept-url>
		<intercept-url pattern="/logout" access="permitAll"></intercept-url>
		<intercept-url pattern="/accessdenied" access="permitAll"></intercept-url>
		<intercept-url pattern="/**" access="hasRole('ROLE_USER')"></intercept-url>
		<form-login login-page="/login" default-target-url="/list" authentication-failure-url="/accessdenied"></form-login>
		<logout logout-success-url="/logout"></logout>

	<authentication-manager alias="authenticationManager">
		<authentication-provider user-service-ref="employeeDAO" />


Also, the complete employee-servlet.xml file look like this:

< ?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <context:annotation-config />
    <context:component-scan base-package="com.howtodoinjava.controller" />

    <bean id="jspViewResolver"
        <property name="viewClass"
        <property name="prefix" value="/WEB-INF/view/"></property>
        <property name="suffix" value=".jsp"></property>

    <bean id="messageSource"
        <property name="basename" value="classpath:messages"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    <bean id="propertyConfigurer"

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"

    <bean id="sessionFactory"
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation">
        <property name="configurationClass">
        <property name="hibernateProperties">

    <bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDaoImpl"></bean>
    <bean id="employeeManager" class="com.howtodoinjava.service.EmployeeManagerImpl"></bean>

    <tx:annotation-driven />
    <bean id="transactionManager"
        <property name="sessionFactory" ref="sessionFactory"></property>


Now we have to update the to implement UserDetailsService interface and override method loadUserByUsername().

package com.howtodoinjava.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import com.howtodoinjava.entity.EmployeeEntity;

public class EmployeeDaoImpl implements EmployeeDAO, UserDetailsService  {

    private SessionFactory sessionFactory;

	public void addEmployee(EmployeeEntity employee) {

	public List<EmployeeEntity> getAllEmployees() {
		return this.sessionFactory.getCurrentSession().createQuery("from Employee").list();

	public void deleteEmployee(Integer employeeId) {
		EmployeeEntity employee = (EmployeeEntity) sessionFactory.getCurrentSession().load(
				EmployeeEntity.class, employeeId);
        if (null != employee) {

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException
		System.out.println("Getting access details from employee dao !!");

		// Ideally it should be fetched from database and populated instance of
		// should be returned from this method
		UserDetails user = new User(username, "password", true, true, true, true, new GrantedAuthority[]{ new GrantedAuthorityImpl("ROLE_USER") });
		return user;

In the above dao, I have used minimal code to show the usage of involved classes and in enterprise application, a proper access to database should be made and the user’s password and its role should be set.

The whole idea is to return the User instance with populated values inside the method. If your have other requirements, then you are free to implements UserDetails interface also and spring will not prevent you from using it.

Test the application

To test the application, simply hit the URL “http://localhost:8080/Spring3HibernateIntegration” in browser window. A login box will appear lie below:


Now login with correct username and password (i.e. lokesh and password) will let you enter into the application and employee management screen will appear. Otherwise access denied page will shown as below:


Happy Learning !!

36 thoughts on “Custom UserDetailsService example for spring 3 security”

  1. Hi Lokesh,

    As per loadUserByUsername(String userName){

    } method shown above, you mentioned based on userName we can fetch User data from DB and populate UserDetails object. I don’t have any confusion here. But my query is where we are matching user entered password with User DB password to authenticate user. This is really where I’m lagging to relate the connection. Can you please help me to clarify this?

    1. We do not compare in our code, it’s spring which does it for us. You mention “AuthenticationProvider” i.e. bean authentication-manager. It internally asks for a ‘UserDetails’ object which is responsibility of “EmployeeDaoImpl” because we mentioned “authentication-provider user-service-ref=”employeeDAO””. Inside framework code, spring matches password stored in “UserDetails” object and one supplied by user in form.

        1. Then you need to pass one extra bean param as below:

          <!-- Configure appropiate encoder -->
          <beans:bean id="encoder" 
          	<beans:constructor-arg name="strength" value="11" />
          <!-- Pass the encoder here -->
          <authentication-manager alias="authenticationManager">
          	<authentication-provider user-service-ref="employeeDAO" />
          	<password-encoder ref="encoder" />

          A good reference is here.

  2. Nice article.
    Do you have some POCs where the user is already authenticated by third party system like LDAP and uses spring security for authorization. I know there are hundred of examples on internet for this, but none of them explains how to create a UserDetails object using HTTP request headers and create appropriate roles based on the group name received in the request header. I tried all pre authentication ways but none of them help as they relay on user details service implementation which has only one method with just one parameter i.e username.

    Any pointer would help.

            1. Isn’t it hibernate already configured in application? If you need something specific.. then probably you need to work on it yourself.. and if facing any problem.. then let me know that specific problem… :-)

  3. Hi I have followed this and got it correct :) Thanku for the post :) Can you help me out the same for security ldap server??

  4. hi i dont want to display that access denied page instead i need to display error message in index.jsp page and i let the user to to login thereonly

    1. Spring docs suggest to use a request parameter in login url itself. They says:

      Maps to the authenticationFailureUrl property of UsernamePasswordAuthenticationFilter. Defines the URL the browser will be redirected to on login failure. Defaults to “/spring_security_login?login_error”, which will be automatically handled by the automatic login page generator, re-rendering the login page with an error message.

      So basically you have to define authentication-failure-url=”/login?error_code=1″ and use it code somewhere in your JSP like this:

      <c:if test=”${param.error_code == ‘1’}”>
      <span><spring:message code=”loginPage.authenticationFailure” /></span>

  5. Hi sir,I used Spring Security UserDetailService in my project and if valid user,its working fine.Iam having some doubts related to Httpsession sir.after the login through spring security,i want to set some flags after successful login ,in loadUserByUsername() again i have to make a call to DB sir.and another one is i want to make some objects into sessionScope,requestScope,is it like General way of Creating HttpSession in spring also sir or any other way is there.because iam working in cluster servers sir,session is always broken sir.Please Help me sir.Thanks

  6. thanks Lokesh for the response but as I see in the link there is the code sourse for jdbc user service. So,I have to do the above changes over this code?thx

    1. Are you sure this is the correct sourcde code. It looks like this one is the same as the one from jdbc user service.

  7. Hi,
    Could you tell me please where i can find the entire source code for this (custom UserDetailService). I didn’t understood very well…this tutorial is based on Spring 3 hibernate integration example? Thanks in advance.

  8. hey i am looking for a example on login authentication with table have user and pass with a no of user in the table
    need to get login by the specific username and password using spring mvc+springsecurity +hibernate please do suggest me

  9. Can you post some example on the below requirement
    my application User is pre-authenticated via third party system and third party system will pass the userid as the request parameter to my application
    I want to use Spring security only for authorization (roles are stored in database)”

    1. Well, first of all that is not the subject of post. I am saying this so other visitors of this page does not get confuse by my argument.
      My take on your question is that it neither will prove effective, if used carelessly. Its not hibernate or JDBC which makes program secure, its how you use them to secure your application.
      JDBC has very low level APIs which makes it more vulnerable if used incorrectly. Hibernate on other hand take care of some basic things, but still you need to do a lot of things extra. to make your application robust and secure.

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Leave a Reply

Your email address will not be published. Required fields are marked *

5 × = twenty five

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>