Spring Security Login Example With Database
By AmarSivas | | Updated : 2021-03-19 | Viewed : 7927 times

The current tutorial will show the example for Spring Security Login With Database. In the previous tutorial, we learned about the Spring Security Login Form Example With In-memory. Here we are tiring to improvise the same example with a database.
Table of Contents:
First, we will look at the required dependencies of maven managed.
Maven Dependencies
<!-- Spring Security lib-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
<!-- Sql driver lib for Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
We used here
In this example, we are going to set up a normal Spring MVC application. So it is required to use Spring 5 MVC related libraries. Please have a look at the Github repository.
Login Form Example With Database
It is time to look at different types of classes to understand this example. Here we need to configure the
We mainly look at
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder())
.usersByUsernameQuery("SELECT U.USER_NAME, U.USER_PASSWORD, U.USER_ENABLED FROM APP_USERS U WHERE U.USER_NAME= ?")
.authoritiesByUsernameQuery("SELECT U.USER_NAME, R.ROLE_NAME FROM APP_USERS U JOIN APP_USER_ROLES UR ON U.USER_ID = UR.USER_ID JOIN APP_ROLES R ON UR.ROLE_ID = R.ROLE_ID WHERE U.USER_NAME = ?");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin").access("hasRole('ROLE_SUPER_ADMIN')")
.antMatchers("/home").access("hasAnyRole('ROLE_USER', 'ROLE_SUPER_ADMIN')")
.and()
.formLogin().loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/accessDenied");
}
}
In the above class, two dependencies are injected i.e.,
Moreover, two more methods
It is required to deploy the generated war in Web App Server like tomcat. The final result will be shown as like the below screenshots. Here we need to pass credentials



Please find the Github Repo for Spring Security Login Form With Database