Thalaivar Thalaivar - 11 months ago 60
Java Question

Spring login form example

I tried searching in Google, but I could not find any good examples where a username and password are checked with a database for authentication purposes.

In further simple words, how can I create a simple login form using Spring and Hibernate where the credentials are checked with the database.


Cam anyone come up with a simple example where I can see how the flow goes and how the input data is passed to hibernate?

Answer Source

At first you should define this file WEB-INF/spring/serurity-context.xml:

<beans:beans xmlns=""
             xmlns:beans="" xmlns:xsi=""

    <http auto-config="true" />

    <beans:bean id="myUserService" class="" />
    <authentication-provider user-service-ref="myUserService" />


Now you should create class and implement interface This interface has one method:

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, org.springframework.dao.DataAccessException

And in this method you can use Hibernate in order to load user by userName. If user does not exists - just throw UsernameNotFoundException, otherwise return new intialized UserDetails instance (there you can provide a lot of stuff like user roles, account expiration date, etc...).

Now comes web.xml:

<web-app xmlns=""

    <display-name>My Webapp</display-name>








If you have any questions or something goes wrong, feel free to ask :)

PS: So with UserDetailsService you don't have to check password of whether user account is active, etc. You just provide spring-security information about user with provided userName and framework validates user itself. If you encode your passwords with MD5 for example, than you can use password-encoder like this:

<beans:bean id="myUserService" class="" />
<authentication-provider user-service-ref="myUserService">
    <password-encoder hash="md5"/>


Now we will dive more deeper in UserService - my (simplified) real world example.

UserService class:

import org.my_company.my_app.domain.User

public class UserService implements UserDetailsService {
    private UserDao userDao;

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

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        // load user
        User user = userDao.getUser(username);

        if (user != null) {

            // convert roles
            List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
            for (Privilege p : user.getPrivileges()) {
                roles.add(new GrantedAuthorityImpl(p.getName()));

            // initialize user
            SecurityUser securityUser = new SecurityUser(
                user.getLdapAuth() ? getLdapPassword(user.getUsername()) : user.getPassword(),
                user.getStatus() != User.Status.NOT_COMMITED, user.getStatus() != User.Status.BLOCKED, true, true,
                roles.toArray(new GrantedAuthority[0])


            return securityUser;
        } else {
            throw new UsernameNotFoundException("No user with username '" + username + "' found!");

Now SecurityUser:

import org.my_company.my_app.domain.User

public class SecurityUser extends {

    private User user;

    public User getUser() {
        return user;

    public void setUser(User user) {
        this.user = user;

    public SecurityUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities) throws IllegalArgumentException {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);

And finally UserDao:

import org.my_company.my_app.domain.User

public class UserDao extends HibernateDaoSupport {

    public User getUser(String username) {
        List users = getHibernateTemplate().find("from User where username = ?", username);
        return users == null || users.size() <= 0 ? null : (User) users.get(0);

As you can see I used HibernateTemplate here.