Spring Boot Security + Hibernate + Custom Form + Login Example

By Dhiraj Ray, 17 December,2016   2216

In this post, let us discuss about auhtenticating user present in database using spring security with form login feature.We will be defining our custom UserDetailService and hibernate with integration to spring to connect to the database. We will continue to use spring boot features similar to previous posts to avoid common configurations.By using spring security we will ensure that our app is secured against Cross Site Request Forgery (CSRF) attacks.In this app also we will have similar configurations as my previos post of Spring security Custom Form Login Example.

Environment Setup

1. JDK 8 2. Spring Boot 3. Intellij Idea/ eclipse 4. Maven

Maven Dependencies

spring-boot-starter-parent: provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for existing dependencies.

spring-boot-starter-web: includes all the dependencies required to create a web app. This will avoid lining up different spring common project versions.

spring-boot-starter-tomcat: enable an embedded Apache Tomcat 7 instance, by default. We have overriden this by defining our version. This can be also marked as provided if you wish to deploy the war to any other standalone tomcat.

tomcat-embed-jasper: provides support for .jsp file rendering.

spring-boot-starter-security: take care of all the required dependencies related to spring security.

<properties> <tomcat.version>8.0.3</tomcat.version> <start-class>spring-boot-example.Application</start-class> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <!--<scope>provided</scope>--> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> </dependency> </dependencies>

Spring Bean Configuration

SpringBootServletInitializer enables process used in Servlet 3.0 using web.xml

@SpringBootApplication: This is a convenience annotation that is equivalent to declaring @Configuration,

@EnableAutoConfiguration and @ComponentScan.

package com.developerstack.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.boot.autoconfigure.SpringBootApplication; @ComponentScan(basePackages = "com.developerstack") @SpringBootApplication public class Application extends SpringBootServletInitializer { private static Class applicationClass = Application.class; public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

Now let us define our main configuration for spring security - SpringSecurityConfig.java.Here we have autowired our service class UserDetailsService.javawhich in turn will get the user details present in the database.In the mean time, we have also made configuration to secure our authentication process with CSRF attack.

package com.developerstack.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Resource(name = "userDetailService") private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login")).and().authorizeRequests() .antMatchers("/dashboard").hasRole("USER").and().formLogin().defaultSuccessUrl("/dashboard") .loginPage("/login").and().logout().permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/*.css"); web.ignoring().antMatchers("/*.js"); } }

This is the class which is reponsible to update the spring security context with valid user and the corresponding role.

package com.developerstack.service.impl; import java.util.Arrays; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; 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.Component; import com.developerstack.dao.UserDao; import com.developerstack.service.UserService; @Component(value = "userDetailService") public class UserDetailServiceImpl implements UserDetailsService, UserService{ @Autowired private UserDao userDao; public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException { com.developerstack.model.UserDetails user = userDao.findUserById(userId); if(user == null){ throw new UsernameNotFoundException("Invalid username or password."); } return new org.springframework.security.core.userdetails.User(user.getId(), user.getPassword(), getAuthority()); } private List getAuthority() { return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")); } public List getUsers() { return userDao.getUserDetails(); } }
package com.developerstack.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.developerstack.dao.UserDao; import com.developerstack.model.UserDetails; @Component public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; public List getUserDetails() { Criteria criteria = sessionFactory.openSession().createCriteria(UserDetails.class); return criteria.list(); } public UserDetails findUserById(String userId) { UserDetails userDetails = null; Criteria criteria = sessionFactory.openSession().createCriteria(UserDetails.class); criteria.add(Restrictions.eq("id", userId)); List entityList = criteria.list(); if(!entityList.isEmpty()) { userDetails = entityList.get(0); } return userDetails; } }

Other Controller and model class have usual configurations and similar to whatever we have defined in the previous post.All these are available in the source code which you can download a the end of the post below.

Client Side

Client side codes are also similar to whatever we have defined in the previous post.All these are available in the source code which you can download a the end of the post below.

DB Configurations

Following is the screenshot:


Run Application

1. Run Application.java as a java application.

2. Hit the url as http://localhost:8080/dashboard but since the user is not authorised yet, user will be redirected to /login as below


3. Now enter any wrong credentials and we can see an error message as follow. This proves our authentication mechanism is working.


4. Enter the username/password as john123/password and hit enter the dashboard page will be rendered.



I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download the source


Spring Security Docs

Spring Security References

Hibernate Docs

Suggest more topics in suggestion section or write your own article and share with your colleagues.

Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.

Further Reading: