Thursday, 15 February 2024

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:

  1. spring.datasource.url=jdbc:h2:mem:testdb
  2. spring.datasource.driverClassName=org.h2.Driver
  3. spring.datasource.username=sa
  4. spring.datasource.password=password
  5. spring.h2.console.enabled=true
  6. spring.h2.console.path=/h2-console
  7. spring.datasource.initialize=true
  8. spring.datasource.platform=h2
  9. spring.datasource.schema=classpath:sql/schema.sql
  10. spring.datasource.data=classpath:sql/data.sql

Step 3: Create Database Schema and Seed Data

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

  1. CREATE TABLE users (
  2. username VARCHAR(50) NOT NULL PRIMARY KEY,
  3. password VARCHAR(100) NOT NULL,
  4. enabled BOOLEAN NOT NULL
  5. );
  6. CREATE TABLE authorities (
  7. username VARCHAR(50) NOT NULL,
  8. authority VARCHAR(50) NOT NULL,
  9. CONSTRAINT fk_authorities_users FOREIGN KEY(username) REFERENCES users(username)
  10. );
  11. INSERT INTO users (username, password, enabled) VALUES ('user', '{bcrypt}$2a$10$0gIvZlNrRpbpzR8UH/2Yh.1Z/8Wlk5.W3kmiMw4vU1UKCvKOfXbi.', true);
  12. INSERT INTO authorities (username, authority) VALUES ('user', 'ROLE_USER');

Step 4: Spring Security Configuration

Create a configuration class to define Spring Security configurations.

  1. <?java
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  6. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  8. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  9. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  10. import org.springframework.security.crypto.password.PasswordEncoder;
  11. import javax.sql.DataSource;
  12. @Configuration
  13. @EnableWebSecurity
  14. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  15. @Autowired
  16. private DataSource dataSource;
  17. @Override
  18. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  19. auth.jdbcAuthentication()
  20. .dataSource(dataSource)
  21. .passwordEncoder(passwordEncoder())
  22. .usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username = ?")
  23. .authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username = ?");
  24. }
  25. @Override
  26. protected void configure(HttpSecurity http) throws Exception {
  27. http.authorizeRequests()
  28. .antMatchers("/").permitAll()
  29. .antMatchers("/admin").hasRole("ADMIN")
  30. .anyRequest().authenticated()
  31. .and().formLogin()
  32. .and().logout().permitAll();
  33. }
  34. @Bean
  35. public PasswordEncoder passwordEncoder() {
  36. return new BCryptPasswordEncoder();
  37. }
  38. }

Step 5: Gradle Configuration

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

  1. // build.gradle
  2. plugins {
  3. id 'org.springframework.boot' version '2.6.3'
  4. id 'io.spring.dependency-management' version '1.0.11.RELEASE'
  5. id 'java'
  6. }
  7. group = 'com.example'
  8. version = '0.0.1-SNAPSHOT'
  9. sourceCompatibility = '11'
  10. repositories {
  11. mavenCentral()
  12. }
  13. dependencies {
  14. implementation 'org.springframework.boot:spring-boot-starter-web'
  15. implementation 'org.springframework.boot:spring-boot-starter-security'
  16. implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
  17. implementation 'mysql:mysql-connector-java'
  18. implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
  19. implementation 'org.springframework.boot:spring-boot-starter-validation'
  20. implementation 'org.springframework.boot:spring-boot-starter-websocket'
  21. testImplementation 'org.springframework.boot:spring-boot-starter-test'
  22. }
  23. test {
  24. useJUnitPlatform()
  25. }

Step 6: Running the Application

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

  1. ./gradlew bootRun

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.

No comments:

Post a Comment

Exploring Amazon Web Services (AWS)

  Compute Services Database Services Storage Services Networking Services Analytics Services Security, Identity, and Compliance Services Ama...