Spring Security form login using database
In this tutorial, we show you how to use database to perform the form-based login authentication in Spring Security.
The last form-based login example will be reused, but the user details are move from XML file to database.
Technologies used :
- Spring 3.0.5.RELEASE
- Spring Security 3.0.5.RELEASE
- Spring JDBC 3.0.5.RELEASE
- MySQL 5.1
P.S We are using MySQL as database.
1. Database Tables
In database, you need to create two tables to store user details and user role details, one to many relationship, one user can contains many roles.
A simple and standard table design for user role relationship. And, you are allow to add extra columns for extra functionality. In additional, the table name and column name are not fixed, you can rename to whatever name.
P.S All scripts in MySQL.
CREATE TABLE `users` ( `USER_ID` INT(10) UNSIGNED NOT NULL, `USERNAME` VARCHAR(45) NOT NULL, `PASSWORD` VARCHAR(45) NOT NULL, `ENABLED` tinyint(1) NOT NULL, PRIMARY KEY (`USER_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user_roles` ( `USER_ROLE_ID` INT(10) UNSIGNED NOT NULL, `USER_ID` INT(10) UNSIGNED NOT NULL, `AUTHORITY` VARCHAR(45) NOT NULL, PRIMARY KEY (`USER_ROLE_ID`), KEY `FK_user_roles` (`USER_ID`), CONSTRAINT `FK_user_roles` FOREIGN KEY (`USER_ID`) REFERENCES `users` (`USER_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Insert data for testing, now an user “mkyong” is created and contains role named “ROLE_USER“.
INSERT INTO mkyongdb.users (USER_ID, USERNAME,PASSWORD, ENABLED) VALUES (100, 'mkyong', '123456', TRUE); INSERT INTO mkyongdb.user_roles (USER_ROLE_ID, USER_ID,AUTHORITY) VALUES (1, 100, 'ROLE_USER');
2. Spring JDBC
Create a data source bean, and connect to database via Spring JDBC.
<beans xmlns="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"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mkyongdb" /> <property name="username" value="root" /> <property name="password" value="password" /> </bean> </beans>
3. Spring Security
In Spring security configuration file, use “jdbc-user-service” tag, and define your query to get the data from database.
<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.0.3.xsd"> <http auto-config="true"> <intercept-url pattern="/welcome*" access="ROLE_USER" /> <form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/loginfailed" /> <logout logout-success-url="/logout" /> </http> <authentication-manager> <authentication-provider> <jdbc-user-service data-source-ref="dataSource" users-by-username-query=" select username,password, enabled from users where username=?" authorities-by-username-query=" select u.username, ur.authority from users u, user_roles ur where u.user_id = ur.user_id and u.username =? " /> </authentication-provider> </authentication-manager> </beans:beans>
4. Demo
See screenshots of this tutorial.
1. If username or password is incorrect.

2. If username or password is correct.


It’s enormous that you are getting ideas from this piece of writing as well as from our dialogue made here.
Excellent weblog here! Also your site a lot up fast! What host are you using?
Can I get your associate hyperlink on your host? I wish my
website loaded up as fast as yours lol
Aw, this was an exceptionally good post. Taking a few minutes and actual effort to create a great
article_ but what can I say_ I put things off a whole lot and
don’t manage to get anything done.
It’s going to be ending of mine day, but before end I am reading this wonderful piece of writing to increase my knowledge.
Mkyong, you rule. Thanks for the great tutorial.
Interesting blog! Is your theme custom made or did you download it from somewhere?
A theme like yours with a few simple tweeks would really make my blog stand out.
Please let me know where you got your theme. Cheers
HI mkyong,
i followed above steps to Spring security Login Form but in that flow i want to add remember-me functionality but i am not able to proceed ,can you please guide me how to fix my issue.
Thanks in advance
Here’s an example, for remember me
http://www.cavalr.com/blog/Spring_MVC_-_Spring_Security_Remember_Me_-_Persistent_Token_Approach
HI mkyong,
i followed above steps to Spring security Login Form but in that flow i want to add ” “functionality but i am not able to proceed ,can you please guide me how to fix my issue.
Thanks in advance
Good respond in return of this issue with firm arguments and
explaining all about that.
Have you ever thought about including a little bit more
than just your articles? I mean, what you say is important and all.
Nevertheless think of if you added some great pictures or video clips to give your posts more,
“pop”! Your content is excellent but with images and videos, this website could certainly
be one of the greatest in its field. Great blog!
You should take part in a contest for one of the greatest blogs online.
I am going to recommend this web site!
It’s very easy to find out any topic on web as compared to books, as I found this piece of writing at this web page.
Here is another good one.
http://www.cavalr.com/blog/Spring_MVC_-_Spring_Security
Hi mkyoung.. i need ur help.. i have a project for multi user application.. how to create login form.. but in case have administrator, teacher and student in 1 login form.. so if login succed.. that have different succes view for admin, teacher and student.. thx 4 read my question.. :)
Hi mykong im getting this info and controller is not called
INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.
Hello mykong thanks for the tutorial.While implementing i get
INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.
wana !
thank MyKyOng for tutorial !
It’s really a exciting article!
at present, i’m using JPA to data access, i don’t how I can use it in tag.
Thank you so much !
at present, i’m using JPA to data access, i don’t how I can use it in authentication-provider
tag.
Thanks for your help, it was very useful.
Hi,
Can we use Spring Security in non-spring based application. If yes, pls. help me how does it work.
Thanks
Hi, That was nice article, please tell me that how to add more than one “Role” in the spring-security.xml??
Hi!
I’m having this error:
Cannot resolve reference to bean ‘dataSource’ while setting bean property ‘dataSource’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘dataSource’ is defined.
Someone can tell me what’s wrong :( ?
Good! All work`s!
Usefull =)
Please upload the same example using Spring and Hibernate.
i am great fan of your work,i am trying to learn Spring so please suggest me a good book from that i can start learning Spring ,keep in mind that i am beginner for spring framework.
Just goto Ameerpet Naresh Institure(Hyderabad) their, you should learn whatever courses you want for less cost and less time period… and belive me or not you sholud will become Master In Spring and Hibernate.
Very good example. But you should also explain the code. I didnt understand where the control go after user click on submit button.I think first it should goes in spring-security.xml. If it goes then in which tag. Uff i m really confused. Can somebody help me…
Hi!
I’ve one query here… I want to authenticate my application using username or email from database. Please tell me the provision how could i achieve the same through the following spring security code.
I tried the same using custom user service also … following is the snippet of my code:
I’ve written the CustomUserDetailsService.java and trying to authenticate using hibernate session factory. But I’m getting error: Error in retrieving user org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here.
I understand by this that no session has established since the application has not been login that’s why this error is, I tried put @Transactional and by hibernateDaoImpl also but no use. Can u please tell me a way how could I authenticate using email and username both instead of username only.
Thanks
Regards,
Jitender Saini
Please get my query again as code was not pasted properly:
Hi!
I’ve one query here… I want to authenticate my application using username or email from database. Please tell me the provision how could i achieve the same through the following spring security code.
I tried the same using custom user service also. following is the snippet of my code:
I’ve written the CustomUserDetailsService.java and trying to authenticate using hibernate session factory. But I’m getting error: Error in retrieving user org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here.
I understand by this that no session has established since the application has not been login that’s why this error is, I tried put @Transactional at hibernateDaoImpl class also but still the error persists. Can u please tell me a way how could I authenticate using email and username both instead of username only.
Thanks
Regards,
Jitender Saini
Hi Mkyong
I am working on project in that we are using password encrytion with key and cipher.
you can see here..
http://www.digizol.org/2009/10/java-encrypt-decrypt-jce-salt.html
i don’t understand how spring security can be used in my project, need help.
or tell me some other way to do it..
Thanks in advance
I want to know how to implement spring security with JCE Encryption – Data Encryption Standard (DES).. please provide example. thanks
dear,
is it necessary to add ROLE_USER to all users in the database in order to make the authentication successful? coz now it doesn’t work
Have this error:
No mapping found for HTTP request with URI [/SpringMVC/] in DispatcherServlet with name ‘mvc-dispatcher’
someone can resolve this problem!!!
avr. 29, 2012 1:34:33 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
Avertissement: No mapping found for HTTP request with URI [/SpringMVC/] in DispatcherServlet with name ‘mvc-dispatcher’
what’s happen!!I have this problem, help please
very good example. I liked and its very easy to understand. Thanks a ton mkyong. Anand singh. Nagpur
I thought that the “password” would be required in the query as well, but it’s in the “select” part of the query, and since the username has to be unique, the spring framework must be comparing it after they get the resultset…. I tried it without “password = ?” and it works fine, as stated in the original article.
Great tutorial as usual! Practical and easy to follow. Would be great to have a best practice example for securing a spring rest service.
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in ServletContext resource [/WEB-INF/spring-database.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property ‘driverClassName’ threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
I have this problem, help me please…
Hi;
I have always got a problem that dispatcher name.
it is that;
WARNING: No mapping found for HTTP request with URI [/SpringExam/welcome] in DispatcherServlet with name ‘mvc-dispatcher’
What is happen?
Thanks,
i facing an issue . when i logout and after that when i paste the welcome page url in browser . it is not going to login page instead of that it is going to welcome directly.
Very nice, up in running in about 10 minutes, worked perfectly. Thank you for the simple (and working) example. Greg
users-by-username-query=”select email, password from user where email = ?”
authorities-by-username-query=”select email, password from user where u.email = ? and u.password = ?” />
or something like that
I dont’t know why it doesn’t add the XML , i’ll try again , sorry for the mass
Mistake , please fix :
Hi , I’m getting an error
Reason: PreparedStatementCallback; SQL [select email, password from user where email = ?]; Column Index out of range, 3 > 2. ; nested exception is java.sql.SQLException: Column Index out of range, 3 > 2.
<!-- Don't set any role restrictions on home -->* Can’t I have the check from only 1 table? user table? 2 tables is a must? I wanna to check email & password from my User table.
* What’s ENABLE for?
* Can I make “user_role” as en enum variable in User? enum.Rule ( ADMIN/USER) and check with that?
Thanks!
I got the same error but adding enable column fixed the issue field
http://forum.springsource.org/showthread.php?54246-where-is-the-quot-standard-Spring-Security-user-data-tables-quot
The data is the same as used by the JdbcDaoImpl class: Code: public static final String DEF_USERS_BY_USERNAME_QUERY = "SELECT username,password,enabled " + "FROM users " + "WHERE username = ?"; public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "SELECT username,authority " + "FROM authorities " + "WHERE username = ?";i am a chinese ,but,thank you !