Main Tutorials

Spring Security + Hibernate XML Example

spring-hibernate-logo

In this tutorial, we will show you how to integrate Hibernate 4 in Spring Security, XML configuration example.

Note
For annotation version, please read this Spring Security + Hibernate Annotation Example.

Technologies used :

  1. Spring 3.2.8.RELEASE
  2. Spring Security 3.2.3.RELEASE
  3. Hibernate 4.2.11.Final
  4. MySQL Server 5.6
  5. JDK 1.6
  6. Maven 3
  7. Eclipse 4.3

Quick Notes

  1. Create a session factory with hibernate4.LocalSessionFactoryBean
  2. Inject session factory into a UserDao
  3. To integrate with Spring Security, create a class that implements the UserDetailsService interface, and loads the User with UserDao
  4. Transaction manager must be declared, else Hibernate won’t work in Spring

1. Project Directory

A final project directory structure.

spring-security-hibernate-directory

2. Project Dependency

List of the project’s dependencies in POM file.

pom.xml

	<properties>
		<spring.version>3.2.8.RELEASE</spring.version>
		<spring.security.version>3.2.3.RELEASE</spring.security.version>
		<jstl.version>1.2</jstl.version>
		<mysql.connector.version>5.1.30</mysql.connector.version>
		<logback.version>1.1.2</logback.version>
		<slf4j.version>1.7.6</slf4j.version>
		<hibernate.version>4.2.11.Final</hibernate.version>
		<dbcp.version>1.4</dbcp.version>
		<servletapi.version>2.5</servletapi.version>
	</properties>

	<dependencies>

		<!-- database pool -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>${dbcp.version}</version>
		</dependency>

		<!-- Hibernate ORM -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
			<exclusions>
			  <exclusion>
				<groupId>commons-logging</groupId>
				<artifactId>commons-logging</artifactId>
			  </exclusion>
			</exclusions>
		</dependency>

		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Spring + aspects -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- ORM integration, e.g Hibernate -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${spring.security.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${spring.security.version}</version>
		</dependency>

		<!-- Spring Security JSP Taglib -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>${spring.security.version}</version>
		</dependency>

		<!-- jstl for jsp page -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>

		<!-- MySql Driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.connector.version}</version>
		</dependency>

		<!-- logging, slf4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>${servletapi.version}</version>
			<scope>provided</scope>
		</dependency>

	</dependencies>

3. User Tables

SQL script to create tables to store user and user’s role.

mysql.sql

CREATE  TABLE users (
  username VARCHAR(45) NOT NULL ,
  password VARCHAR(60) NOT NULL ,
  enabled TINYINT NOT NULL DEFAULT 1 ,
  PRIMARY KEY (username));

CREATE TABLE 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));

INSERT INTO users(username,password,enabled)
VALUES ('mkyong','$2a$10$04TVADrR6/SPLBjsK0N30.Jf5fNjBugSACeGv1S69dZALR7lSov0y', true);
INSERT INTO users(username,password,enabled)
VALUES ('alex','$2a$10$04TVADrR6/SPLBjsK0N30.Jf5fNjBugSACeGv1S69dZALR7lSov0y', true);

INSERT INTO user_roles (username, role)
VALUES ('mkyong', 'ROLE_USER');
INSERT INTO user_roles (username, role)
VALUES ('mkyong', 'ROLE_ADMIN');
INSERT INTO user_roles (username, role)
VALUES ('alex', 'ROLE_USER');

4. User Model + Hibernate XML Mapping

Model classes and its’ XML mapping file.

User.java

package com.mkyong.users.model;

import java.util.HashSet;
import java.util.Set;

public class User {
	
	private String username;
	private String password;
	private boolean enabled;
	private Set<UserRole> userRole = new HashSet<UserRole>(0);
	
	//getter and setter methods
}
UserRole.java

package com.mkyong.users.model;

public class UserRole{

	private Integer userRoleId;
	private User user;
	private String role;

	//getter and setter methods
}
Users.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.mkyong.users.model.User" table="users" catalog="test">
        <id name="username" type="string">
            <column name="username" length="45" />
            <generator class="assigned" />
        </id>
        <property name="password" type="string">
            <column name="password" length="60" not-null="true" />
        </property>
        <property name="enabled" type="boolean">
            <column name="enabled" not-null="true" />
        </property>
        <set name="userRole" table="user_roles" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="username" length="45" not-null="true" />
            </key>
            <one-to-many class="com.mkyong.users.model.UserRole" />
        </set>
    </class>
</hibernate-mapping>
UserRoles.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.mkyong.users.model.UserRole" table="user_roles" catalog="test">
        <id name="userRoleId" type="java.lang.Integer">
            <column name="user_role_id" />
            <generator class="identity" />
        </id>
        <many-to-one name="user" class="com.mkyong.users.model.User" fetch="select">
            <column name="username" length="45" not-null="true" />
        </many-to-one>
        <property name="role" type="string">
            <column name="role" length="45" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

5. DAO Class

Create a UserDao class to load users from the database, via Hibernate.

UserDao.java

package com.mkyong.users.dao;

import com.mkyong.users.model.User;

public interface UserDao {

	User findByUserName(String username);

}
UserDaoImpl.java

package com.mkyong.users.dao;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;

import com.mkyong.users.model.User;

public class UserDaoImpl implements UserDao {

	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public User findByUserName(String username) {

		List<User> users = new ArrayList<User>();

		users = getSessionFactory().getCurrentSession()
			.createQuery("from User where username=?")
			.setParameter(0, username).list();

		if (users.size() > 0) {
			return users.get(0);
		} else {
			return null;
		}

	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}

6. UserDetailsService

Create a custom UserDetailsService, load user from UserDao, then build the user’s authorities.

Note
Example is reference from this Spring’s JdbcDaoImpl
MyUserDetailsService.java

package com.mkyong.users.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
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 com.mkyong.users.dao.UserDao;
import com.mkyong.users.model.UserRole;

public class MyUserDetailsService implements UserDetailsService {

	private UserDao userDao;

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

		com.mkyong.users.model.User user = userDao.findByUserName(username);
		List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());

		return buildUserForAuthentication(user, authorities);
		

	}

	// Converts com.mkyong.users.model.User user to
	// org.springframework.security.core.userdetails.User
	private User buildUserForAuthentication(com.mkyong.users.model.User user, 
		List<GrantedAuthority> authorities) {
		return new User(user.getUsername(), 
			user.getPassword(), user.isEnabled(), 
                        true, true, true, authorities);
	}

	private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {

		Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

		// Build user's authorities
		for (UserRole userRole : userRoles) {
			setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
		}

		List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

		return Result;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}

7. Spring Security XML

Read the comments, it should be self-explanatory.

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

	<!-- enable use-expressions -->
	<http auto-config="true" use-expressions="true">
		<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />

		<!-- access denied page -->
		<access-denied-handler error-page="/403" />
		<form-login 
		    login-page="/login" 
		    default-target-url="/welcome"
			authentication-failure-url="/login?error" 
			username-parameter="username"
			password-parameter="password" />
		<logout logout-success-url="/login?logout" />
		<!-- enable csrf protection -->
		<csrf />
	</http>

	<authentication-manager>
		<authentication-provider user-service-ref="myUserDetailsService" >
			<password-encoder hash="bcrypt" />    
		</authentication-provider>
	</authentication-manager>

</beans:beans>
spring-database.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<!-- MySQL data source -->
	<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" />
		<property name="password" value="password" />
	</bean>

	<!-- Hibernate session factory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
				<value>orm/Users.hbm.xml</value>
				<value>orm/UserRoles.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
		    <props>
			<prop key="hibernate.dialect">
                           org.hibernate.dialect.MySQL5Dialect
                        </prop>
			<prop key="hibernate.format_sql">true</prop>
			<prop key="hibernate.show_sql">true</prop>
		    </props>
		</property>
	</bean>

	<bean id="userDao" class="com.mkyong.users.dao.UserDaoImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<bean id="myUserDetailsService" 
                class="com.mkyong.users.service.MyUserDetailsService">
		<property name="userDao" ref="userDao" />
	</bean>

	<!-- MUST have transaction manager, using aop and aspects  -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<tx:advice id="txAdvice" transaction-manager="transactionManager">
	    <tx:attributes>
		<tx:method name="get*" read-only="true" />
		<tx:method name="find*" read-only="true" />
		<tx:method name="*" />
	    </tx:attributes>
	</tx:advice>

	<aop:config>
	    <aop:pointcut id="userServicePointCut"
		expression="execution(* com.mkyong.users.service.*Service.*(..))" />
	    <aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut" />
	</aop:config>

</beans>

Done.

Note
Those JSP, web.xml and controller files are omitted, it’s quite a standard code, if you are interested on it, please download the full source code at the end of the article.

8. Project Demo

The following video demo is for the Spring Security database login with JDBC tutorial. Since this tutorial is generating the same output, but using the Hibernate to load Users, so the video demo is reused.

8.1 Access a password protected page : http://localhost:8080/spring-security-hibernate/admin , a login page is displayed.

spring-security-hibernate1

8.2 Enter user “mkyong” and password “123456”.

spring-security-hibernate2

8.3 Try access /admin page with user “alex” and password “123456”, a 403 page will be displayed.

spring-security-hibernate3

Download Source Code

Download it – spring-security-hibernate.zip (30 KB)

References

  1. Spring ORM – Hibernate
  2. Spring Hibernate4 LocalSessionFactoryBean JavaDoc
  3. Spring Hibernate3 LocalSessionFactoryBean JavaDoc
  4. Spring Transaction Management
  5. Hibernate ORM documentation
  6. Spring Security Form Login Using Database, with JDBC
  7. Hibernate : No Session Found For Current Thread

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
42 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
niwas
8 years ago

every time I am getting the username and password incorrect

Hao
4 years ago

Hi sir, thanks a lot of your turtorial. Can you explain help me about file spring-security.xml. I’m not understand “user-service-ref=’myUserDetailsService’ “. Is it need to declare something ?. When i run my project, i get an error “No bean named ‘myUserDetailsService’ “. Please, help me, thank you !

Ram
7 years ago

com.mkyong.users.model.User user = userDao.findByUserName(username);
List authorities = buildUserAuthority(user.getUserRole());
return buildUserForAuthentication(user, authorities);

Better to handle null check for user object reference before use.

Prateek Ashtikar
7 years ago

Hello, I dont see XML application code is running. When I enter username and password, I dont see anything happening..

Ved Prakash Mishra
8 years ago

its not logging , saying invalid crdentails

Varun Sharma
8 years ago

Hi Mkyong, I come to your website quite often to find answers to my problems while building web portals. I must say I have never been disappointed. I thank you for all the efforts that you have put in to create this website.

With regards,
Varun

Thomas Yuen
8 years ago

I got the web app running and am able to login using the spring security. my question is that i did not see @TRANSACTIONAL in the UserDaoImpl.findByUserName(). Can you explain why? It is because when I made another service class to make the call to UserDaoImpl.findByUserName(), I got “HTTP Status 500 – Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread” and the following is new server class:

import com.apexiot.users.dao.UserDao;

import com.apexiot.users.model.User;
import com.apexiot.users.service.UserCRUDService;

@Service
public class UserCRUDServiceImpl implements UserCRUDService {

private SessionFactory sessionFactory;
private UserDao userDao;

@Override

@Transactional(propagation=Propagation.REQUIRES_NEW)
public User findUserByUserName(String userName)
{
Session session = getSessionFactory().openSession();
User user = userDao.findByUserName(userName);
session.close();
return user;
}
}

Another question is that when I add the @Transactional to the UserDaoImp() as follow:

@SuppressWarnings(“unchecked”)
@Transactional(propagation=Propagation.NESTED)
public User findByUserName(String username) {

List users = new ArrayList();

Session session = getSessionFactory().getCurrentSession();
users = session.createQuery(“from User where username=?”).setParameter(0, username).list();

if (users.size() > 0) {
return users.get(0);
} else {
return null;
}

}

If I call the findByUserName from my service, the jdbc transaction was closed when the call return back to the service before the session is closed.

Thank you for our tutorial.

Best regards

DEADForMojo666 (NOT AUTOLIKE)
8 years ago

Eliminar catalog=’test’
.. (without catalog) entry.

Thiagarajan Ramanathan
8 years ago

if i try with the url “http://localhost:8080/spring-security-hibernate/admin/” (added ‘/’ at last) takes me directly to admin page where as when i try http://localhost:8080/spring-security-hibernate/admin it takes me to login page. If i understood correctly it should not show admin page without logging but i am able to see admin page by simply adding / at last. How to resolve that issue.

Thiagarajan Ramanathan
8 years ago

I found the answer.

just changed /admin** to /admin/** which resolved the issue.

vishank
8 years ago

Hi Mkyong,

When enter the username as “mkyong” and password as “123456”. it gives the error page 404 and the url is like

http://localhost:8080/spring-security-hibernate/j_spring_security_check

Please help me.

SantaSauce
8 years ago

How did you generate the hashes for your password?

I tried the following code…

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

System.out.println(passwordEncoder.encode(“123456”));

And got the following output…

$2a$10$I.6i7LDl5SxC7FRAIQ5rlOlE.79YJ.mHVQ0NE4J52tPBShLm2IHr.

Daniel Jab?o?ski
8 years ago

You must delete catalog=”test” from Users.hbm.xml and UserRoles.hbm.xml

Mehrdad Norouzi
8 years ago

mohan ram said :

When enter the username as “mkyong” and password as “123456”. It say username and password incorrect.

I
thought database declaration may get overrides as hkmehandiratta said
in comment, i tried by removing “catalog=test” but still getting same
username and password as incorrect.

i am said too ..

Sudheer@Hyd
8 years ago

For Logout need to add logout-url like below

Sid
8 years ago

Someone help, I used the same implementation but everytime I try to login i get a 404 Error on j_spring_security_check stating

org.springframework.web.servlet.PageNotFound – Request method ‘POST’ not supported

divya
4 years ago
Reply to  Sid

check db connection. username password wrong for db

Evgen
8 years ago

Hi Mkyong. Do you know how use Spring 4 with Spring Security 3?

human
9 years ago

hi,

what is the salt. How is the password generated? I want to add registration feature.

Felipe
9 years ago

Hi

I’m using Spring 2.5 and hibernate 3 (Flex and Java application).
I’m trying to use Spring 4 and Hibernate 4.

How can I extend the OpenSessionInViewFilter for avoid LazyLoad problems?

The problem:

org.hibernate.LazyInitializationException: could not initialize proxy – no Session
With the Spring 2.5 and Hibernate 3 that error doesn’t exist.

Regards

Wareeezer
9 years ago

Hi! I’m creating a maven multimodule project, i want to use the spring security and i have this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘securityConfig’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.security.core.userdetails.UserDetailsService hu.cnw.hrm.config.security.SecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userDetailsService)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4770)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.security.core.userdetails.UserDetailsService hu.cnw.hrm.config.security.SecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userDetailsService)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
… 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userDetailsService)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
… 24 more

john muteti
9 years ago

Hi, can you post a tutorial in java hibernate soring mvc on how to create user and insert there records to the database. All login tutorials lack that part. Thankyou.

zakaria
9 years ago

I tried it. This dependency should be added as well, otherwise it keeps on throwing a run-time exception.

org.springframework

spring-web

${org.springframework-version}

silly buyer
9 years ago

Hi Mkyong, is there a tutorial for user registration page where you use it with hibernate? Thanks for this very informative tutorial.

David Anthony Hines
9 years ago

How do I replace the spring mvc components with struts 1.x?

David Anthony Hines
9 years ago

How do I use this with struts?

Nguyen Hoang Yen
9 years ago

Hi Mkyong! Thank you for this post. I tried to follow your step but I’ve got some errors. Please help me!
1. When I ran on IE with 403 case, IE didn’t show my customized 403 page. IE showed their own 403 page. I unchecked “Show friendly HTTP error messages” in IE tool option. It worked. But I think that it will happen on user browser. Is there any solution for this case thoroughly?
2. Firstly, I logged in with mkyong account. It was okie. I logged out. After that, I logged in with alex account. It accepted too???
Against, I logged in with alex account -> 403 page -> logged out -> logged in with mkyong account -> show welcome page??
I think that log out process have problem. Please help me fix this! Many thanks!

pchoucine
9 years ago
ROUSSI Abdelghani
9 years ago

I have this error when i try to run my application , can you guys tell me what’s wrong ( I followed the tutorial step by step )

Caused
by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
‘org.springframework.security.web.DefaultSecurityFilterChain#0’: Cannot
resolve reference to bean
‘org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0’
while setting constructor argument with key [4]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
‘org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0’:
Cannot resolve reference to bean
‘org.springframework.security.authentication.ProviderManager#0’ while
setting bean property ‘authenticationManager’; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
‘org.springframework.security.authentication.ProviderManager#0’: Cannot
resolve reference to bean
‘org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0’
while setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
‘org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0’:
FactoryBean threw exception on object creation; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name ‘org.springframework.security.authenticationManager’:
Cannot resolve reference to bean
‘org.springframework.security.authentication.dao.DaoAuthenticationProvider#0’
while setting constructor argument with key [0]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
‘org.springframework.security.authentication.dao.DaoAuthenticationProvider#0’:
Cannot resolve reference to bean ‘myUserDetaillService’ while setting
bean property ‘userDetailsService’; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean
named ‘myUserDetaillService’ is defined
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:359)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:636)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:140)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1133)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1036)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
… 26 common frames omitted

Antuan Develle Claude
9 years ago

I recommend using the exact versions of jar shown in the POM displayed at the top of this page. Doing otherwise will resort in many anomalous errors.

Mohan Ram
9 years ago

Hi Mkyong,

When enter the username as “mkyong” and password as “123456”. It say username and password incorrect.

I thought database declaration may get overrides as hkmehandiratta said in comment, i tried by removing “catalog=test” but still getting same username and password as incorrect.

Please guide me.

Mehrdad Norouzi
8 years ago
Reply to  Mohan Ram

Is the problem solved?
Please let me know.

Antuan Develle Claude
9 years ago
Reply to  Mohan Ram

I’m sure you have fixed this by now, but just for others who might have had this problem.

1.)123456 is the password for both users in this sample. Attempting to use what you see in the database will end in error as that is the password AFTER encoding.

2.) Try adding to your spring-database.xml file.

hkmehandiratta
9 years ago

Hi Mkyong.. Please remove the ‘catalog’ entry from Users.hbm.xml.. The ‘catalog=test’ overrides the database name given in spring-security.xml. I was using the database as ‘testdb’ whereas with catalog, hibernate was trying to find ‘users’ table in ‘test’ db… leading to error.
Users.hbm.xml
.. (without catalog) entry.

Regards
-Hiten

Zimyx
9 years ago

Broken link to Jdbc example in part 6