Spring MVC: Security with MySQL and Hibernate

Spring-Security-logo
Spring has a lot of different modules. All of them are useful for the concrete purposes. Today I’m going to talk about Spring Security. This module provides flexible approach to manage permitions for access to different parts of web-application. In the post I’ll examine integration of Spring MVC, Hibernate, MySQL with Spring Security.

A regular case for any web-application is separation of functionality between some user groups. E.g. user with a “moderator” role can edit existing records in a database. An user with “admin” role can do the same thing as the user with “moderator” role plus create new records. In Spring MVC application permition management can be implemented with the Spring Security.

The goal

As an example I will use sample Spring MVC application with Hibernate. The users and their roles will be stored in a database. MySQL will be used as the database. I’m going to create three tables: users, roles, user_roles. As you might guess the user_roles table is an intermediary table.
In the application will be two roles: moderator and admin. There will be several pages with access for the moderator and for the admin.

Preparation

In order to make Spring Security available in a project, just add following dependencies in a pom.xml file:

		
		
			org.springframework.security
			spring-security-core
			3.1.3.RELEASE
		
		
			org.springframework.security
			spring-security-web
			3.1.3.RELEASE
		
		
			org.springframework.security
			spring-security-config
			3.1.3.RELEASE
		

I have to create three tables in the database and insert several records there.

CREATE TABLE `roles` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `role` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

CREATE TABLE `users` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `login` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

CREATE TABLE `user_roles` (
  `user_id` int(6) NOT NULL,
  `role_id` int(6) NOT NULL,
  KEY `user` (`user_id`),
  KEY `role` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

And here is a code for the roles and users:

INSERT INTO hibnatedb.roles (role) VALUES ('admin'), ('moderator');

INSERT INTO hibnatedb.users (login, password) VALUES ('moder', '111111'), ('adm', '222222');

INSERT INTO hibnatedb.user_roles (user_id, role_id) VALUES (1, 2), (2, 1);

Main part

The complete structure of project has the following structure:

Spring-Security-Project-Structure

Since you can find this project on GitHub, I’ll omit some things which are out of the current theme. I want to start from the heart of every web-project, I mean web.xml file. Spring Security is based on simple filters, so I need to add declaration of the filter in the deployment descriptor:

...
	
		springSecurityFilterChain
		org.springframework.web.filter.DelegatingFilterProxy
	
	
		springSecurityFilterChain
		/*
	
...

Now it’s time to create entities for the users and roles tables:

@Entity
@Table(name="users")
public class User {
	
	@Id
	@GeneratedValue
	private Integer id;
	
	private String login;
	
	private String password;
	
	@OneToOne(cascade=CascadeType.ALL)
	@JoinTable(name="user_roles",
		joinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")},
		inverseJoinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")}
	)
	private Role role;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}	

}

And

@Entity
@Table(name="roles")
public class Role {
	
	@Id
	@GeneratedValue
	private Integer id;
	
	private String role;
	
	@OneToMany(cascade=CascadeType.ALL)
	@JoinTable(name="user_roles", 
		joinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")},
		inverseJoinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")}
	)
	private Set userRoles;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public Set getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(Set userRoles) {
		this.userRoles = userRoles;
	}
	
}

Each entity class requires DAO and Service layer.

public interface UserDAO {
	
	public User getUser(String login);

}

And

@Repository
public class UserDAOImpl implements UserDAO {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	private Session openSession() {
		return sessionFactory.getCurrentSession();
	}

	public User getUser(String login) {
		List userList = new ArrayList();
		Query query = openSession().createQuery("from User u where u.login = :login");
		query.setParameter("login", login);
		userList = query.list();
		if (userList.size() > 0)
			return userList.get(0);
		else
			return null;	
	}

}

Respectively for the Role class:

public interface RoleDAO {
	
	public Role getRole(int id);

}

And

@Repository
public class RoleDAOImpl implements RoleDAO {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	public Role getRole(int id) {
		Role role = (Role) getCurrentSession().load(Role.class, id);
		return role;
	}

}

The same pairs for the service layer:

public interface UserService {
	
	public User getUser(String login);

}

And

@Service
@Transactional
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDAO userDAO;

	public User getUser(String login) {
		return userDAO.getUser(login);
	}

}

Respectively for the Role class:

public interface RoleService {
	
	public Role getRole(int id);

}

And

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private RoleDAO roleDAO;

	public Role getRole(int id) {
		return roleDAO.getRole(id);
	}

}

Everything above was just mechanical, routine code. Now let’s work on the Spring Security code. In order to plug in Spring Security into the project I have to create CustomUserDetailsService class and implement UserDetailsService interface.

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sprsec.dao.UserDAO;

@Service
@Transactional(readOnly=true)
public class CustomUserDetailsService implements UserDetailsService {
	
	@Autowired
	private UserDAO userDAO;	

	public UserDetails loadUserByUsername(String login)
			throws UsernameNotFoundException {
		
		com.sprsec.model.User domainUser = userDAO.getUser(login);
		
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		return new User(
				domainUser.getLogin(), 
				domainUser.getPassword(), 
				enabled, 
				accountNonExpired, 
				credentialsNonExpired, 
				accountNonLocked,
				getAuthorities(domainUser.getRole().getId())
		);
	}
	
	public Collection getAuthorities(Integer role) {
		List authList = getGrantedAuthorities(getRoles(role));
		return authList;
	}
	
	public List getRoles(Integer role) {

		List roles = new ArrayList();

		if (role.intValue() == 1) {
			roles.add("ROLE_MODERATOR");
			roles.add("ROLE_ADMIN");
		} else if (role.intValue() == 2) {
			roles.add("ROLE_MODERATOR");
		}
		return roles;
	}
	
	public static List getGrantedAuthorities(List roles) {
		List authorities = new ArrayList();
		
		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		return authorities;
	}

}

The main purpose of the class is to map User class of the application to the User class of Spring Security. This is one of the killer-feature of the Spring Security. In this way you can adapt any kind of Spring MVC application to usage of the Security module.

Controllers and Views

One of the most frequent question regarding Spring Security is how to create a custom login form. The answer is simple enough. You need to create a JSP file with a the form, and specify there action attribute ().

Login-page-spring-security

The most part of the URL-mapping depends on spring-security.xml file:

...
	
	
		
		
		
		
		
		
	
	
	
		
			
		
	
...

As you can see, I specified URLs for the: login page, default page after success login, error page for the situations when credentials are invalid. Also I declared URLs which require some access permitions. And the most important thing is a declaration of the authentication-manager. Through this Spring Security will use database to identify users and their roles.
In order to implement the logout functionality, you have to place the link with the follow href attribute on one of the pages:


Controllers:

@Controller
public class LinkNavigation {
	
	@RequestMapping(value="/", method=RequestMethod.GET)
	public ModelAndView homePage() {
		return new ModelAndView("home");
	}
	
	@RequestMapping(value="/index", method=RequestMethod.GET)
	public ModelAndView indexPage() {
		return new ModelAndView("home");
	}
	
	@RequestMapping(value="/sec/moderation", method=RequestMethod.GET)
	public ModelAndView moderatorPage() {
		return new ModelAndView("moderation");
	}
	
	@RequestMapping(value="/admin/first", method=RequestMethod.GET)
	public ModelAndView firstAdminPage() {
		return new ModelAndView("admin-first");
	}
	
	@RequestMapping(value="/admin/second", method=RequestMethod.GET)
	public ModelAndView secondAdminPage() {
		return new ModelAndView("admin-second");
	}

}

And

@Controller
public class SecurityNavigation {
	
	@RequestMapping(value="/user-login", method=RequestMethod.GET)
	public ModelAndView loginForm() {
		return new ModelAndView("login-form");
	}
	
	@RequestMapping(value="/error-login", method=RequestMethod.GET)
	public ModelAndView invalidLogin() {
		ModelAndView modelAndView = new ModelAndView("login-form");
		modelAndView.addObject("error", true);
		return modelAndView;
	}
	
	@RequestMapping(value="/success-login", method=RequestMethod.GET)
	public ModelAndView successLogin() {
		return new ModelAndView("success-login");
	}

}

Views you can see on GitHub.

Pay you attention to adding of @ImportResource(“classpath:spring-security.xml”) in the WebAppConfig java class.

Summary

I think this article will help you to dive into Spring Security. I used here Hibernate and MySQL since such combination of technologies isn’t used often in other tutorials in the internet. Probably you noticed that I used some XMLs in the project, that’s because currently there is no ways to implement all these stuff using annotation based approach.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • http://www.agung-setiawan.com Agung Setiawan

    great example of common usage of Spring Security
    thank you…

  • Arun

    I followed your spring security example. I am getting error like http://localhost:8081/Spring3MVC/j_spring_security_check is not avilable. (j_spring_security_check handler missing)

    • Fruzenshtein

      Looks like you didn’t create the spring-security.xml or you didn’t add the security filter in the web.xml

  • Ricky

    Thanks. Could you also post your spring-servlet.xml so that it is easier to understand how are you specifying the CustomUserService bean and its properties? The AutoWired userDAO in CustomeUserService remains null for me.

    • Fruzenshtein

      I don’t use spring-servlet.xml, instead of it I use java-based configuration: WebAppConfig.class
      There is a link to this class in the article
      You can find the entire code of application by the link: https://github.com/Fruzenshtein/security-spr

  • Chris

    Hi. I have one question: Why you ignore the service layer for User (UserService) that you’ve created earlier and you refer directly to the UserDAO in your CustomUserDetailsService in line 27:
    com.sprsec.model.User domainUser = userDAO.getUser(login);

    Why you need UserService anway in general if you are doing it this way?

    • Fruzenshtein

      I chose this approach because I think that service layer should interact only with DAO layer, and controllers should work in their turn with service layer

      What do you think about this?

      • Chris

        Make sens :)
        I personally prefer interact to the service layer in this particular example, but i’m a newbie :)

        Thx for response!

  • Vivin Paliath

    Nice tutorial! It was very helpful! I’m curious; why is getGrantedAuthorities static in CustomUserDetailsService?

    • Fruzenshtein

      Thanks
      Because this method is related to the logic of the class

  • Saravanan

    I tried spring security example. I am getting error like
    java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?

    Please let me know what is wrong in my application

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Hi,

      Try to compare the classes from com.sprsec.init package which I placed on GitHub with appropriate classes on your local computer

      • Mike

        Hi Alex,

        Thank you for the excellent tutorial. However, I’m getting the same error as Saravanan after the server is successfully started with no errors.

        I’ve compared the 2 files in init package but didn’t see any changes relevant to the error. In fact, I used your code and still got the same error. It seems to me the Inititializer-onStartup method is not triggered.

        Btw, I don’t know if this is relevant but I have to add ‘maven-compiler-plugin’ to set the project to use 1.6. Otherwise, it always sets back to 1.5. I also followed your tut on how to create a dynamic web project with maven (http://fruzenshtein.com/setup-of-dynamic-web-project-using-maven/) but without the plugin, the project always set to 1.5. I can’t use 1.5 because package javax.annotation.Resource is not available.

        Any suggestions?

        • http://fruzenshtein.com/ Alex Zvolinskiy

          Hi Mike,

          Exception which occured said to you that you don’t have ContextLoaderListener in your Initializaer class.

          Check your pom.xml file and try to add into it:

          security-spr

          maven-compiler-plugin
          2.3.2

          1.7
          1.7

          • Mike

            Thank you for your prompt response. I was a little confused since your Github code doesn’t have that plugin in the pom.xml but I think the plugin is necessary for the code to successfully compile.

            I was experimenting with Apache TomEE and I think this is a bug with this new web application server. I had to switch back to Apache Tomcat to get this Inititializer-onStartup method triggered. FYI, I did have ContextLoaderListener added to the servlet context.

            On a side note, even with Apache Tomcat, I must do a Maven > Update Projects after a Run as > Maven clean to have everything run properly.

            Thanks again for the wonderful post. Keep up the good work!

          • http://fruzenshtein.com/ Alex Zvolinskiy

            Mike, I’m very happy that you have solved the problem

            If you are developer you should know that some times you can encounter with absolutely strange situations.

            Have a good day

          • vijay Kumar

            Hi Alex,

            Now my application is running but when I enter correct login/ password I am getting error invalid login/password. i used moder/111111 and adm/222222. But I am getting same error. Please let me know why I am getting this error even after entering correct login/passsword

          • http://fruzenshtein.com/ Alex Zvolinskiy

            Maybe you didn’t populate the database tables with appropriate?

          • carlj776

            Hi Alex , i have this error :

            rg.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: private com.sprsec.service.CustomUserDetailsService com.sprsec.init.SecurityConfig.customUserDetailsService; nested exception is java.lang.IllegalArgumentException: Can not set com.sprsec.service.CustomUserDetailsService field com.sprsec.init.SecurityConfig.customUserDetailsService to com.sun.proxy.$Proxy32

            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)

            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)

            i can’t autowire beans from rootconfig… but i don’t know why!!
            Thanks

          • Tim Worcester

            I am getting this same error as well. I was able to get around it by changing the CustomUserDetailsService to CustomUserDetailsServiceImpl and creating an interface instance of CustomUserDetailsService. CustomUserDetailsServiceImpl will have to implement both UserDetailsService and CustomUserDetailsService. That caused my tomcat instance to start without errors.

            I believe this may break something else though as when I post the form information the login page just redirects back to itself and never actually reaches the loadUserByUsername method. Fix one bug, find two more right?

          • vijay Kumar

            I am also facing same problem. When I use mvn war:war command with and tag set to 1.7 I get above error. If I remove these tags I am able to execute mvn war:war command but my application gives ContextLoaderListener error in eclipse with tomcat 6. Now I have put the war file on standalone tomcat 7 server. Now it is running fine. Can you please explain me this behaviour

  • softwaresolutions

    I could not find the spring-security.xml on your github project. I think that file also contains the mysql connection credentials?

  • softwaresolutions

    Can you share all the lib folder that you are using? Or even better, if you could zip the complete project so we can import it. Just to let you know that I am a beginner in Java web development, and it takes really long time with configurations. Not that I am time limited, but I mean too many configurations and easy to make mistakes. Thanks

    • http://fruzenshtein.com/ Alex Zvolinskiy

      All libs are declared in the pom.xml file in the root folder of application.
      If you are beginner you’d better to start with some more easier tutorials or even books.

  • Guest

    Hi,
    I’m missing hibernate class(Entity) for user_roles table.

    • http://fruzenshtein.com/ Alex Zvolinskiy

      You don’t need this entity, just table in a DB

  • adisree

    hi i am using jsp,spring,hibernat,mysql and eclipse juno in my project,i
    dont know mavin ,how can i use your code, how i delete,mavin files
    from ur attachment code,pls help me…
    or pther wise pls provide in attachment same code with out mavin…..pls,pls,pls

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Man, I’d better to read how to work with Maven. It will really help you and increase a speed of development

  • yunus

    I got this error :

    The method addListener(ContextLoaderListener) is undefined for the type ServletContext

    what’s wrong?

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Did you import all required dependencies?

    • Arvind Das

      Hi Yunus ,I also received same error.I had this comfiguration present in my pom.xml

      javax.servlet
      servlet-api
      2.5
      provided

      while I also had

      javax.servlet
      javax.servlet-api
      3.0.1
      provided

      Removing first one resolved my issue
      Cheers!

  • duy hoang nguyen

    I got error: No bean named ‘springSecurityFilterChain’ is defined. How can I fix this?

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Look at the web.xml file in the article

    • ankur bhat

      Hi duy, look at my reply above. probably this should fix your error.

  • softwaresolutions

    I am playing around with this example, bthw, very helpful. The question is how do i add css styles to this example? I think we need to map the css somehow, i saw on google some example by using servlet mapping, but cannot make it work in this example. Can you please give me some help here? Regards

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Try to google “css resource spring mvc”
      And you will find the answer

  • ankur bhat

    Thanks for this wonderful thorough tutorial.

    Note: In spring-security.xml we have :

    Here probably you are referencing the bean with id:-customUserDetailsService, but since it aint in the file one might face bean not initialized run time exception.

    You might want to add the following in the same file. This would resolve that issue:-

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Thanks for the comment
      In this tutorual I use java based config for Spring MVC and I don’t need to declare some beans in XML

    • carlos alfonso cortina arce

      dont you get a problem that the userDao at customuserdetailsservice get null for the autowired? i had the problem that you mention and i used your idea but then i got the aforementioned problem. also if i add a bean for userdao i get an error of multiple beans definition. could you help me?

  • carlos alfonso cortina arce

    i keep getting Null at the field @Autowired private UserDAO userDAO in CustomUserDetailsService does anyone know why?

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Check carefully your WebAppConfig file (Enable Web MVC, package to scun), and then look at your DAO.

      • carlos alfonso cortina arce

        im using xml config so i used the idea of ankur bhat and yes it worked to erase an error but at the end i got this problem.

        • Sandeep

          I am getting same problem how did you correct this problem. I am using xml configuration. Please help me out.

  • Saravanan

    Thanks for this great tutorial. It is working fine.

  • Sandip Bhaumik

    Hello,

    I am getting this error.

    Aug 27, 2013 3:39:14 PM org.springframework.web.context.ContextLoader initWebApplicationContext

    SEVERE: Context initialization failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘roleDAOImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.sprsec.dao.impl.RoleDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class com.sprsec.init.WebAppConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.hibernate4.LocalSessionFactoryBean com.sprsec.init.WebAppConfig.sessionFactory()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class com.sprsec.init.WebAppConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.sprsec.init.WebAppConfig.dataSource()] threw exception; nested exception is java.lang.StackOverflowError

    Any idea on what I had done wrong.

    Thanks,
    Sandip

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Maybe RoleDAOImpl class isn’t annotated with @Repository

      • Sandip Bhaumik

        Sorry for late reply but yes, it is annotated with @Repository

      • Sandip Bhaumik

        Alex, Can you please let me know where is the issue?

        • http://fruzenshtein.com/ Alex Zvolinskiy

          Sandip it’s hard to say where you have made a mistake. I don’t see entire code and so on. In a pretty large projects like this you can do some small stuff in different way and the project won’t be work

          I can’t help you in this situation

    • Mykola Bova

      Hi Team,

      I issued similar problem.

      Not sure if I have a real solution.
      But – at least workaround.

      I removed all webapps and war files for webapps folder of tomcat.
      It helped!
      Please let us know if you will find a “real” solution.

      Mykola

      • http://fruzenshtein.com/ Alex Zvolinskiy

        Don’t forget to clean up a Tomcat work directory during development. When you don’t do it, it causes such problems

  • Munkhdalai

    Hello, i tried to work this tutorial but i received 404 error on web browser. Aslo i don’t receive any error on tomcat console. Any idea?

  • Munkhdalai

    Hello. i tried to work this tutorial but i got this error.

    Aug 30, 2013 3:59:58 PM org.apache.catalina.core.ApplicationContext log

    INFO: Spring WebApplicationInitializers detected on classpath: [com.sprsec.init.Initializer@4d7e038b, com.sprsec.init.SecurityInitializer@c1ac26c]

    java.lang.IllegalStateException: Duplicate Filter registration for ‘springSecurityFilterChain’. Check to ensure the Filter is only configured once.

    at org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.registerFilter(AbstractSecurityWebApplicationInitializer.java:177)

    at org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.insertSpringSecurityFilterChain(AbstractSecurityWebApplicationInitializer.java:109)

    at org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.onStartup(AbstractSecurityWebApplicationInitializer.java:83)

    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:180)

    Where is problem?

    • Munkhdalai

      Alex Zvolinskiy , Do you have any idea?

      • http://fruzenshtein.com/ Alex Zvolinskiy

        Seems you declared SecurityFilter twice in web.xml

        • Hui Liu

          I’m having the same issue using the Spring Tool Suite. I wonder if it’s somehow inserting it’s own filter/filter-mapping into the web.xml,because I only see 1 of each.

  • Munkhdalai

    Also, Could you share again xml based config for this tutorial?

    • http://fruzenshtein.com/ Alex Zvolinskiy

      No
      Just java based

      • Munkhdalai

        Plsee? i think xml based config is more clear.

  • Sandeep

    I am using xml configuration, I am getting null instance of UserDao in CustomUserDetails service. Help me out.

  • Andrea Dorigo

    I don’t get why, when I update an user, the associated role got deleted…

  • Gaurav Shah

    brilliant

  • Марио Ѓурчески

    Can anyone upload the whole project because I have problems with uploading the existing project from GitHub…
    Thanks…

  • Sandeep vashisth

    Thanks for this amazing tutorial, can you plz provides this tutorial with REST service and pure html5.

    • http://fruzenshtein.com/ Alex Zvolinskiy

      I don’t specialize on HTML5, so I can’t

  • Alex S. Popovici

    Hi! I had a problem actually logging in with adm or moder. This was because the sql script from your post starts the increment at 5 for the tables, but the sql insert into the join table links the user with id 1 and id 2. So go in the db and modify the users and roles tables or just the user_roles records. Sharing this cause I’ve seen someone in the comments running into the same problem.

    Anyway, superb post!

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Well I hope your comment will be helpful for someone
      Thanks

  • Chetan Mastamardi

    Hi, I am trying this example after running this example i’m getting the following errors in console. I tried it to resolve this one by copying Mysql-connector Jar file in to Tomacat/lib directory even though it is not working. i am using Tomcat 7, Please anybody who got this problem and solved let me help to resolve this.

    Feb 11, 2014 10:16:14 AM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Context [/HiberSecureLogin] startup failed due to previous errors

    Feb 11, 2014 10:16:14 AM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
    SEVERE: The web application [/HiberSecureLogin] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.

    Feb 11, 2014 10:16:14 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
    SEVERE: The web application [/HiberSecureLogin] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.

    Thanks and Regards
    Chetan

  • saurabh

    can you help me with this error plzz…
    ” cannot resolve symbol @EnableWebSecurity” similarly WebSecurityConfigurerAdapter and so on at SecurityConfig.java …

    SpringSecurity jars are added.
    are added.
    thanx..

  • xiaoyu

    hello, I have added your code in my existing project, but I am confused there are several pom.xml in my project and I don’t know which one should be edited, and there is already a spring-servlet.xml, should I add the spring-security.xml in your exemple or just add the codes in the existing one? Tanks a lot

  • xiaoyu

    hi; if i have already a project; are these all i need to add ?