DEV Community

AdityaPratapBhuyan
AdityaPratapBhuyan

Posted on

Spring Boot Security with JDBC Authentication

Spring Boot

Step 1: Set Up Spring Boot Project

First, make sure you have Spring Boot installed. Then, create a new Spring Boot project using Spring Initializr.

You can use either the Spring Initializr website or your IDE to create the project. Include the following dependencies:

  • Spring Web
  • Spring Security
  • Spring JDBC
  • H2 Database (or any other database driver you prefer)

Step 2: Configure JDBC Authentication

In this step, we'll configure Spring Security to use JDBC authentication.

  1. Database Configuration: Create a schema and a table for storing user credentials. For demonstration purposes, we'll use an H2 in-memory database.
  2. Security Configuration: Configure Spring Security to use JDBC authentication.

Below is a sample application.properties file:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

spring.datasource.initialize=true
spring.datasource.platform=h2
spring.datasource.schema=classpath:sql/schema.sql
spring.datasource.data=classpath:sql/data.sql
Enter fullscreen mode Exit fullscreen mode

Step 3: Create Database Schema and Seed Data

Create schema.sql and data.sql files in the src/main/resources/sql directory.

CREATE TABLE users (
    username VARCHAR(50) NOT NULL PRIMARY KEY,
    password VARCHAR(100) NOT NULL,
    enabled BOOLEAN NOT NULL
);

CREATE TABLE authorities (
    username VARCHAR(50) NOT NULL,
    authority VARCHAR(50) NOT NULL,
    CONSTRAINT fk_authorities_users FOREIGN KEY(username) REFERENCES users(username)
);

INSERT INTO users (username, password, enabled) VALUES ('user', '{bcrypt}$2a$10$0gIvZlNrRpbpzR8UH/2Yh.1Z/8Wlk5.W3kmiMw4vU1UKCvKOfXbi.', true);

INSERT INTO authorities (username, authority) VALUES ('user', 'ROLE_USER');
Enter fullscreen mode Exit fullscreen mode

Step 4: Spring Security Configuration

Create a configuration class to define Spring Security configurations.

<?java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
            .dataSource(dataSource)
            .passwordEncoder(passwordEncoder())
            .usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username = ?")
            .authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username = ?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/admin").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and().formLogin()
            .and().logout().permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Gradle Configuration

Ensure you have the necessary dependencies in your build.gradle file:

// build.gradle

plugins {
    id 'org.springframework.boot' version '2.6.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'mysql:mysql-connector-java'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-websocket'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

Enter fullscreen mode Exit fullscreen mode

Step 6: Running the Application

You can run the application using Gradle with the following command:

./gradlew bootRun
Enter fullscreen mode Exit fullscreen mode

Now, your Spring Boot application with JDBC authentication is ready to use!

Conclusion

In this tutorial, you've learned how to set up Spring Boot Security with JDBC authentication. You configured the database, created necessary tables, and defined Spring Security configurations to authenticate users using JDBC. Feel free to expand on this foundation to add more features and customize the security aspects of your application.

Top comments (0)