Spring Security is the Spring framework module that handles authentication (who you are) and authorization (what you can access). It places a chain of security filters in front of every request, so unauthenticated users never reach protected controllers. It is used in applications such as online banking to protect customer data, passwords and account operations. It provides login mechanisms, password hashing, role-based access control and protection against common web attacks.
Features
- Authentication with form login, HTTP Basic and database-backed users
- Authorization using roles (e.g.
CUSTOMER) on URLs - Password hashing with BCrypt, so plain-text passwords are never stored
- Filter-chain based protection for every incoming request
- Built-in protection against CSRF, session fixation and clickjacking
- Easy integration with Spring Data JPA and MySQL
Spring Security Authentication Types
| Type | Explanation | Typical use |
|---|---|---|
| Form Login | Spring Security shows a login page (/login). The user enters a username and password, and a session is created after success. |
Browser-based banking portals |
| HTTP Basic | The client sends Authorization: Basic base64(username:password) with every request. No login page, no session needed. |
REST APIs, Postman testing |
| In-Memory Authentication | Users are defined in code or configuration and held in memory. | Demos and quick prototypes |
| Database (JDBC/JPA) Authentication | Users and encrypted passwords are loaded from a database through UserDetailsService. |
Real applications such as banking |
This example uses Database authentication (via UserDetailsService) with Form Login and HTTP Basic enabled together.
Hands-on Experiment: Online Banking Login System with Spring Security
To build a Spring Boot application in which bank customers register, log in with credentials stored in MySQL, and access protected account information, while public URLs stay open.
Software/Tools Required
- JDK 17
- Spring Boot 3.x
- Maven
- MySQL 8.x
- IDE (IntelliJ IDEA / Eclipse / STS)
- Postman
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
Open https://start.spring.io and select:
| Setting | Value |
|---|---|
| Project | Maven |
| Language | Java |
| Spring Boot | 3.3.x |
| Group | com.example |
| Artifact | online-banking-security |
| Packaging | Jar |
| Java | 17 |
| Dependencies | Spring Web, Spring Security, Spring Data JPA, MySQL Driver |
Click Generate, extract the zip and open it in your IDE.
Step 2: Project Structure
online-banking-security
├── pom.xml
└── src/main
├── java/com/example/bankingsecurity
│ ├── OnlineBankingSecurityApplication.java
│ ├── entity
│ │ └── Customer.java
│ ├── repository
│ │ └── CustomerRepository.java
│ ├── service
│ │ ├── CustomerService.java
│ │ └── SecurityConfig.java
│ └── controller
│ ├── AuthController.java
│ └── AccountController.java
└── resources
└── application.properties
Step 3: Creating the files according to project structure
package com.example.bankingsecurity.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.math.BigDecimal;
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String fullName;
@Column(nullable = false, unique = true)
private String username;
// Accepted in requests, never returned in responses
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Column(nullable = false)
private String password;
@Column(nullable = false, unique = true)
private String email;
private String accountNumber;
private BigDecimal balance;
private String role;
public Customer() {
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getAccountNumber() { return accountNumber; }
public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; }
public BigDecimal getBalance() { return balance; }
public void setBalance(BigDecimal balance) { this.balance = balance; }
public String getRole() { return role; }
public void setRole(String role) { this.role = role; }
}
package com.example.bankingsecurity.repository;
import com.example.bankingsecurity.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Optional<Customer> findByUsername(String username);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
}
package com.example.bankingsecurity.service;
import com.example.bankingsecurity.entity.Customer;
import com.example.bankingsecurity.repository.CustomerRepository;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.concurrent.ThreadLocalRandom;
/**
* Handles customer registration and tells Spring Security
* how to load a customer from the database during login.
*/
@Service
public class CustomerService implements UserDetailsService {
private final CustomerRepository customerRepository;
private final PasswordEncoder passwordEncoder;
public CustomerService(CustomerRepository customerRepository, PasswordEncoder passwordEncoder) {
this.customerRepository = customerRepository;
this.passwordEncoder = passwordEncoder;
}
public Customer register(Customer customer) {
if (isBlank(customer.getFullName()) || isBlank(customer.getUsername())
|| isBlank(customer.getPassword()) || isBlank(customer.getEmail())) {
throw new IllegalArgumentException("fullName, username, password and email are required");
}
if (customerRepository.existsByUsername(customer.getUsername())) {
throw new IllegalArgumentException("Username already exists");
}
if (customerRepository.existsByEmail(customer.getEmail())) {
throw new IllegalArgumentException("Email already registered");
}
customer.setId(null);
customer.setPassword(passwordEncoder.encode(customer.getPassword()));
customer.setRole("CUSTOMER");
customer.setAccountNumber("ACC" + ThreadLocalRandom.current().nextLong(1_000_000_000L, 9_999_999_999L));
customer.setBalance(new BigDecimal("10000.00"));
return customerRepository.save(customer);
}
public Customer getByUsername(String username) {
return customerRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("Customer not found: " + username));
}
// Called by Spring Security whenever a customer tries to log in
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Customer customer = getByUsername(username);
return User.withUsername(customer.getUsername())
.password(customer.getPassword())
.roles(customer.getRole())
.build();
}
private boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
}
package com.example.bankingsecurity.service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
/**
* Security rules for the Online Banking application.
* Kept in the service package because only four packages are used.
*/
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// CSRF is disabled only to keep Postman testing simple in this introduction
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/register", "/api/public/**").permitAll()
.requestMatchers("/api/account/**").hasRole("CUSTOMER")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults()) // for Postman / API clients
.formLogin(Customizer.withDefaults()); // login page at /login for browsers
return http.build();
}
}
package com.example.bankingsecurity.controller;
import com.example.bankingsecurity.entity.Customer;
import com.example.bankingsecurity.service.CustomerService;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
// Protected: only a logged-in CUSTOMER can reach these URLs
@RestController
@RequestMapping("/api/account")
public class AccountController {
private final CustomerService customerService;
public AccountController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("/profile")
public Customer profile(Authentication authentication) {
return customerService.getByUsername(authentication.getName());
}
@GetMapping("/balance")
public Map<String, Object> balance(Authentication authentication) {
Customer customer = customerService.getByUsername(authentication.getName());
return Map.of(
"accountNumber", customer.getAccountNumber(),
"balance", customer.getBalance());
}
}
package com.example.bankingsecurity.controller;
import com.example.bankingsecurity.entity.Customer;
import com.example.bankingsecurity.service.CustomerService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class AuthController {
private final CustomerService customerService;
public AuthController(CustomerService customerService) {
this.customerService = customerService;
}
// Public: open a new banking customer account
@PostMapping("/auth/register")
public ResponseEntity<?> register(@RequestBody Customer customer) {
try {
Customer saved = customerService.register(customer);
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}
// Public: no login required
@GetMapping("/public/info")
public Map<String, String> info() {
return Map.of(
"bank", "Secure Online Bank",
"message", "Public endpoint - no login required");
}
}
package com.example.bankingsecurity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OnlineBankingSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(OnlineBankingSecurityApplication.class, args);
}
}
spring.application.name=online-banking-security
server.port=8080
# MySQL (database is created automatically if it does not exist)
spring.datasource.url=jdbc:mysql://localhost:3306/banking_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
# JPA / Hibernate
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=trueCode language: PHP (php)
Step 4: Run the OnlineBankingSecurityApplication





