Form-based login lets users sign in through an HTML form instead of a browser pop-up. Spring Security reads the submitted username and password and checks them against the database. After a successful login it creates a session, so the user stays signed in until logout. It is used because hospital staff need a branded login page and a controlled logout.
Features
- Custom login page, with your own HTML and styling
- Dedicated login processing URL (
POST /login) - Success and failure redirects (
/dashboard,/login?error) - Logout that invalidates the session and deletes the cookie
- Session-based authentication
- Role-based access (ADMIN, DOCTOR, NURSE, RECEPTIONIST)
- BCrypt password hashing
Form Login Authentication Types
- In-Memory: Users are defined in code with
InMemoryUserDetailsManager. It is good for demos, but users are lost on restart. - JDBC: Spring’s
JdbcUserDetailsManagerreads users from a fixed table layout (users,authorities). - Custom UserDetailsService (used here): Your own service loads users from your own entity and table. It gives full control over fields and roles.
Hands-on Experiment: Building a Hospital Staff Login Portal with Form-Based Authentication
Aim: To build a Spring Boot application that secures hospital pages with a custom login form, a dashboard and a logout.
Software/Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ/Eclipse/VS Code), Postman
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
- Project: Maven | Language: Java | Spring Boot: 3.3.x
- Group:
com.example| Artifact:hospital-portal| Packaging: Jar | Java: 17 - Dependencies: Spring Web, Spring Security, Thymeleaf, Spring Data JPA, Validation, MySQL Driver
Step 2: Project Structure
hospital-portal
├── pom.xml
└── src/main
├── java/com/example/hospitalportal
│ ├── HospitalPortalApplication.java
│ ├── entity/Staff.java
│ ├── repository/StaffRepository.java
│ ├── service/StaffService.java
│ ├── service/SecurityConfig.java
│ ├── controller/PortalController.java
│ └── controller/StaffController.java
└── resources
├── application.properties
└── templates/login.html, dashboard.html
Step 3: Creating the files according to the project structure
package com.example.hospitalportal.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 jakarta.validation.constraints.NotBlank;
@Entity
@Table(name = "staff")
public class Staff {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(nullable = false)
private String fullName;
@NotBlank
@Column(nullable = false, unique = true)
private String username;
// accepted in requests, never returned in responses
@NotBlank
@Column(nullable = false)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
// ADMIN, DOCTOR, NURSE or RECEPTIONIST
@NotBlank
@Column(nullable = false)
private String role;
private boolean enabled = true;
public Staff() {
}
public Staff(String fullName, String username, String password, String role) {
this.fullName = fullName;
this.username = username;
this.password = password;
this.role = role;
}
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 getRole() { return role; }
public void setRole(String role) { this.role = role; }
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
}
package com.example.hospitalportal.repository;
import com.example.hospitalportal.entity.Staff;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface StaffRepository extends JpaRepository<Staff, Long> {
Optional<Staff> findByUsername(String username);
boolean existsByUsername(String username);
}
package com.example.hospitalportal.service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login").permitAll()
.requestMatchers("/api/staff", "/api/staff/**").hasRole("ADMIN")
.anyRequest().authenticated())
.formLogin(form -> form
.loginPage("/login") // custom login page (GET)
.loginProcessingUrl("/login") // form submit (POST)
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/dashboard", true)
.failureUrl("/login?error")
.permitAll())
.logout(logout -> logout
.logoutUrl("/logout") // POST /logout
.logoutSuccessUrl("/login?logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll())
// CSRF is skipped here only so the URLs can be tested from Postman.
// Remove this line in production: the HTML forms already send the CSRF token.
.csrf(csrf -> csrf.ignoringRequestMatchers("/login", "/logout", "/api/**"));
return http.build();
}
}
package com.example.hospitalportal.service;
import com.example.hospitalportal.entity.Staff;
import com.example.hospitalportal.repository.StaffRepository;
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.util.List;
import java.util.Set;
@Service
public class StaffService implements UserDetailsService {
private static final Set<String> ROLES = Set.of("ADMIN", "DOCTOR", "NURSE", "RECEPTIONIST");
private final StaffRepository staffRepository;
private final PasswordEncoder passwordEncoder;
public StaffService(StaffRepository staffRepository, PasswordEncoder passwordEncoder) {
this.staffRepository = staffRepository;
this.passwordEncoder = passwordEncoder;
}
// Called by Spring Security when the login form is submitted
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Staff staff = staffRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("Staff not found: " + username));
return User.builder()
.username(staff.getUsername())
.password(staff.getPassword())
.roles(staff.getRole())
.disabled(!staff.isEnabled())
.build();
}
public Staff register(Staff staff) {
if (staffRepository.existsByUsername(staff.getUsername())) {
throw new IllegalArgumentException("Username already exists: " + staff.getUsername());
}
String role = staff.getRole().toUpperCase();
if (!ROLES.contains(role)) {
throw new IllegalArgumentException("Role must be one of " + ROLES);
}
staff.setRole(role);
staff.setPassword(passwordEncoder.encode(staff.getPassword()));
return staffRepository.save(staff);
}
public List<Staff> findAll() {
return staffRepository.findAll();
}
public Staff findByUsername(String username) {
return staffRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("Staff not found: " + username));
}
public void createDefaultStaff() {
if (!staffRepository.existsByUsername("admin")) {
register(new Staff("System Administrator", "admin", "admin123", "ADMIN"));
}
if (!staffRepository.existsByUsername("drsmith")) {
register(new Staff("Dr. John Smith", "drsmith", "doctor123", "DOCTOR"));
}
}
}
package com.example.hospitalportal.controller;
import com.example.hospitalportal.service.StaffService;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class PortalController {
private final StaffService staffService;
public PortalController(StaffService staffService) {
this.staffService = staffService;
}
@GetMapping("/")
public String home() {
return "redirect:/dashboard";
}
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/dashboard")
public String dashboard(Authentication authentication, Model model) {
model.addAttribute("staff", staffService.findByUsername(authentication.getName()));
return "dashboard";
}
}
package com.example.hospitalportal.controller;
import com.example.hospitalportal.entity.Staff;
import com.example.hospitalportal.service.StaffService;
import jakarta.validation.Valid;
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.List;
import java.util.Map;
@RestController
@RequestMapping("/api/staff")
public class StaffController {
private final StaffService staffService;
public StaffController(StaffService staffService) {
this.staffService = staffService;
}
@PostMapping
public ResponseEntity<?> register(@Valid @RequestBody Staff staff) {
try {
return ResponseEntity.status(HttpStatus.CREATED).body(staffService.register(staff));
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}
@GetMapping
public List<Staff> getAll() {
return staffService.findAll();
}
}
package com.example.hospitalportal;
import com.example.hospitalportal.service.StaffService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class HospitalPortalApplication {
public static void main(String[] args) {
SpringApplication.run(HospitalPortalApplication.class, args);
}
// Creates two demo staff accounts on first start
@Bean
CommandLineRunner seedStaff(StaffService staffService) {
return args -> staffService.createDefaultStaff();
}
}
spring.application.name=hospital-portal
server.port=8080
# MySQL (database is created automatically if missing)
spring.datasource.url=jdbc:mysql://localhost:3306/hospital_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.thymeleaf.cache=falseCode language: PHP (php)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hospital Staff Login</title>
<style>
body { font-family: Arial, sans-serif; background: #eaf3f8; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
.card { background: #fff; padding: 32px; width: 320px; border-radius: 10px; box-shadow: 0 4px 14px rgba(0,0,0,.12); }
h2 { margin: 0; color: #0b5d82; }
.sub { color: #666; margin: 4px 0 18px; }
label { display: block; margin-top: 12px; font-size: 14px; }
input { width: 100%; padding: 9px; margin-top: 4px; box-sizing: border-box; border: 1px solid #bbb; border-radius: 5px; }
button { width: 100%; margin-top: 18px; padding: 10px; background: #0b5d82; color: #fff; border: 0; border-radius: 5px; font-size: 15px; cursor: pointer; }
.msg { padding: 8px; border-radius: 5px; font-size: 14px; margin-bottom: 8px; }
.error { background: #fde2e2; color: #a12626; }
.ok { background: #dff3e3; color: #206a32; }
</style>
</head>
<body>
<div class="card">
<h2>Hospital Management Portal</h2>
<p class="sub">Staff Login</p>
<div class="msg error" th:if="${param.error}">Invalid username or password.</div>
<div class="msg ok" th:if="${param.logout}">You have been logged out successfully.</div>
<form th:action="@{/login}" method="post">
<label for="username">Username</label>
<input type="text" id="username" name="username" required autofocus>
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
</div>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hospital Staff Login</title>
<style>
body { font-family: Arial, sans-serif; background: #eaf3f8; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
.card { background: #fff; padding: 32px; width: 320px; border-radius: 10px; box-shadow: 0 4px 14px rgba(0,0,0,.12); }
h2 { margin: 0; color: #0b5d82; }
.sub { color: #666; margin: 4px 0 18px; }
label { display: block; margin-top: 12px; font-size: 14px; }
input { width: 100%; padding: 9px; margin-top: 4px; box-sizing: border-box; border: 1px solid #bbb; border-radius: 5px; }
button { width: 100%; margin-top: 18px; padding: 10px; background: #0b5d82; color: #fff; border: 0; border-radius: 5px; font-size: 15px; cursor: pointer; }
.msg { padding: 8px; border-radius: 5px; font-size: 14px; margin-bottom: 8px; }
.error { background: #fde2e2; color: #a12626; }
.ok { background: #dff3e3; color: #206a32; }
</style>
</head>
<body>
<div class="card">
<h2>Hospital Management Portal</h2>
<p class="sub">Staff Login</p>
<div class="msg error" th:if="${param.error}">Invalid username or password.</div>
<div class="msg ok" th:if="${param.logout}">You have been logged out successfully.</div>
<form th:action="@{/login}" method="post">
<label for="username">Username</label>
<input type="text" id="username" name="username" required autofocus>
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
</div>
</body>
</html>
Step 4: Run the HospitalPortalApplication


