Spring Security Login Example With Database

By | | Updated : 2021-03-19 | Viewed : 1457 times

Spring Security Login Example With Database

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.

First, we will look at the required dependencies of maven managed.

Maven Dependencies

Required 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 spring-security-config for using of spring security module. And Sql driver library(mysql-connector-java) for mysql is 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 SecurityInitializer.java, WebAppInitializer.java, and WebMvcConfig.java. So to understand more about these classes please look at Spring Security Login Form Example With In-memory

We mainly look at WebSecurityConfig class as it is required to understand it.

WebSecurityConfig.java
@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., Datasource and BCryptPasswordEncoder. Datasource is for only communicating database and all where BCryptPasswordEncoder is used for matching the password with encrypted password existed in the database.

Moreover, two more methods(configAuthentication and configure) are written here. configAuthentication() method handles verification of the user and password provided by the User. And configure() method contains the configuration of URLs and authorization details. If Authentications fails the redirected URLs are also configured here.

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 User: amarsivas and Password: amarsivas.

Spring Security Login Example With Database
Spring Security Login Example With Database
Spring Security Login Example With Database

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

Leave A Reply