Chapter 2: Basic Authentication
Introduction
This chapter teaches you how to configure the most common authentication methods: Form Login and HTTP Basic. You will also learn how to store users in a database with secure passwords.
🎯 Chapter Objectives
By the end of this chapter, you will know how to:
- ✅ Configure form-based authentication
- ✅ Configure HTTP Basic for APIs
- ✅ Implement UserDetailsService with the database
- ✅ Use BCrypt to encode passwords
- ✅ Customize login/logout pages
1. Basic Configuration
Dependencies
<!-- pom.xml -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- For Thymeleaf + Security extras -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
</dependencies>
Minimal Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/home", "/css/**", "/js/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.permitAll()
)
.logout(logout -> logout
.logoutSuccessUrl("/login?logout")
.permitAll()
)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
2. In-Memory Users (Test)
For Development Only
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults())
.build();
}
@Bean
public UserDetailsService userDetailsService(PasswordEncoder encoder) {
UserDetails user = User.builder()
.username("user")
.password(encoder.encode("password"))
.roles("USER")
.build();
UserDetails admin = User.builder()
.username("admin")
.password(encoder.encode("admin123"))
.roles("ADMIN", "USER")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
warning
InMemoryUserDetailsManager is for testing and development only. In production, use a database!
3. Database Users
3.1 User Entity
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String username;
@Column(nullable = false)
private String password;
@Column(unique = true, nullable = false)
private String email;
private boolean enabled = true;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles = new HashSet<>();
}
3.2 Role Entity
@Entity
@Table(name = "roles")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String name; // ROLE_USER, ROLE_ADMIN
public Role(String name) {
this.name = name;
}
}
3.3 Repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
}
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(String name);
}
3.4 CustomUserDetails
public class CustomUserDetails implements UserDetails {
private final User user;
public CustomUserDetails(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return user.isEnabled();
}
// To access the complete User entity
public User getUser() {
return user;
}
}
3.5 CustomUserDetailsService
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException(
"User not found: " + username
));
return new CustomUserDetails(user);
}
}
3.6 Configuration with the Database
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final CustomUserDetailsService userDetailsService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/register", "/css/**", "/js/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.permitAll()
)
.logout(logout -> logout
.logoutSuccessUrl("/login?logout")
.deleteCookies("JSESSIONID")
.permitAll()
)
.userDetailsService(userDetailsService)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
}
4. Registration Service
UserService
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
private final PasswordEncoder passwordEncoder;
@Transactional
public User registerUser(String username, String email, String password) {
// Checks
if (userRepository.existsByUsername(username)) {
throw new RuntimeException("This username already exists");
}
if (userRepository.existsByEmail(email)) {
throw new RuntimeException("This email is already in use");
}
// Create user
User user = new User();
user.setUsername(username);
user.setEmail(email);
user.setPassword(passwordEncoder.encode(password)); // ← Encoding!
user.setEnabled(true);
// Assign default USER role
Role userRole = roleRepository.findByName("ROLE_USER")
.orElseThrow(() -> new RuntimeException("ROLE_USER not found"));
user.getRoles().add(userRole);
return userRepository.save(user);
}
@Transactional
public void promoteToAdmin(Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
Role adminRole = roleRepository.findByName("ROLE_ADMIN")
.orElseThrow(() -> new RuntimeException("ROLE_ADMIN not found"));
user.getRoles().add(adminRole);
userRepository.save(user);
}
}
5. HTTP Basic for API
Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable()) // Disable for REST API
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/**").authenticated()
)
.httpBasic(Customizer.withDefaults()) // ← HTTP Basic
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.build();
}
}
Test with cURL
# Without authentication
curl http://localhost:8080/api/users
# 401 Unauthorized
# With authentication
curl -u user:password http://localhost:8080/api/users
# 200 OK + data
# With explicit header
curl -H "Authorization: Basic dXNlcjpwYXNzd29yZA==" http://localhost:8080/api/users
caution
HTTP Basic sends credentials encoded in Base64 (NOT encrypted!). ALWAYS use HTTPS in production!
6. Custom Login Pages
Controller
@Controller
public class AuthController {
@GetMapping("/login")
public String loginPage() {
return "login"; // templates/login.html
}
@GetMapping("/register")
public String registerPage(Model model) {
model.addAttribute("user", new RegisterRequest());
return "register";
}
@PostMapping("/register")
public String register(@Valid @ModelAttribute("user") RegisterRequest request,
BindingResult result,
RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
return "register";
}
try {
userService.registerUser(
request.getUsername(),
request.getEmail(),
request.getPassword()
);
redirectAttributes.addFlashAttribute("success", "Registration successful!");
return "redirect:/login";
} catch (Exception e) {
result.rejectValue("username", "error", e.getMessage());
return "register";
}
}
}
Login Template (Thymeleaf)
<!-- templates/login.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
<link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
<div class="login-container">
<h1>Login</h1>
<!-- Messages -->
<div th:if="${param.error}" class="alert alert-danger">
Incorrect username or password.
</div>
<div th:if="${param.logout}" class="alert alert-info">
You have been logged out.
</div>
<div th:if="${success}" class="alert alert-success" th:text="${success}"></div>
<!-- Form -->
<form th:action="@{/login}" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
</div>
<div class="form-group">
<label>
<input type="checkbox" name="remember-me"> Remember me
</label>
</div>
<button type="submit">Log in</button>
</form>
<p>Don't have an account? <a th:href="@{/register}">Sign up</a></p>
</div>
</body>
</html>
Remember-Me Configuration
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
// ... other configs
.rememberMe(remember -> remember
.key("uniqueAndSecretKey") // Signature key
.tokenValiditySeconds(86400 * 7) // 7 days
.userDetailsService(userDetailsService)
)
.build();
}
7. Accessing the Logged-In User
In a Controller
@RestController
@RequestMapping("/api")
public class ProfileController {
// Method 1: Principal
@GetMapping("/me")
public String getCurrentUser(Principal principal) {
return "Logged in as: " + principal.getName();
}
// Method 2: Authentication
@GetMapping("/profile")
public Map<String, Object> getProfile(Authentication authentication) {
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
User user = userDetails.getUser();
return Map.of(
"username", user.getUsername(),
"email", user.getEmail(),
"roles", authentication.getAuthorities()
);
}
// Method 3: @AuthenticationPrincipal
@GetMapping("/details")
public User getDetails(@AuthenticationPrincipal CustomUserDetails userDetails) {
return userDetails.getUser();
}
// Method 4: SecurityContextHolder (anywhere)
@GetMapping("/static")
public String getFromContext() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth.getName();
}
}
In Thymeleaf
<!-- With thymeleaf-extras-springsecurity6 -->
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<!-- Display username -->
<p>Welcome, <span sec:authentication="name">User</span>!</p>
<!-- Display based on role -->
<div sec:authorize="hasRole('ADMIN')">
<a href="/admin">Administration</a>
</div>
<div sec:authorize="hasRole('USER')">
<a href="/profile">My Profile</a>
</div>
<!-- Display if authenticated -->
<div sec:authorize="isAuthenticated()">
<form th:action="@{/logout}" method="post">
<button type="submit">Log out</button>
</form>
</div>
<!-- Display if NOT authenticated -->
<div sec:authorize="isAnonymous()">
<a href="/login">Login</a>
</div>
8. Error Handling
Custom AccessDeniedHandler
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException ex) throws IOException {
// For REST API
if (request.getRequestURI().startsWith("/api/")) {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().write("{\"error\": \"Access denied\"}");
} else {
// For web pages
response.sendRedirect("/access-denied");
}
}
}
Configuration
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
// ... other configs
.exceptionHandling(ex -> ex
.accessDeniedHandler(customAccessDeniedHandler)
.authenticationEntryPoint((request, response, authException) -> {
if (request.getRequestURI().startsWith("/api/")) {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("{\"error\": \"Not authenticated\"}");
} else {
response.sendRedirect("/login");
}
})
)
.build();
}
9. Initial Data
DataInitializer
@Component
@RequiredArgsConstructor
public class DataInitializer implements CommandLineRunner {
private final RoleRepository roleRepository;
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
@Override
@Transactional
public void run(String... args) {
// Create roles if absent
if (roleRepository.count() == 0) {
roleRepository.save(new Role("ROLE_USER"));
roleRepository.save(new Role("ROLE_ADMIN"));
roleRepository.save(new Role("ROLE_MANAGER"));
}
// Create a default admin if no users
if (userRepository.count() == 0) {
Role adminRole = roleRepository.findByName("ROLE_ADMIN").orElseThrow();
Role userRole = roleRepository.findByName("ROLE_USER").orElseThrow();
User admin = new User();
admin.setUsername("admin");
admin.setEmail("admin@example.com");
admin.setPassword(passwordEncoder.encode("admin123"));
admin.setEnabled(true);
admin.setRoles(Set.of(adminRole, userRole));
userRepository.save(admin);
}
}
}
10. Summary
Key Points
| Concept | Description |
|---|---|
| Form Login | Web form-based authentication |
| HTTP Basic | Authorization header for API |
| UserDetailsService | Interface to load users |
| PasswordEncoder | Password encoding (BCrypt) |
| CustomUserDetails | Adapt User to UserDetails |
Typical Configuration
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.permitAll()
)
.logout(logout -> logout.permitAll())
.build();
}
Checklist
✅ Encode passwords with BCrypt
✅ Implement UserDetailsService for the database
✅ Create CustomUserDetails if needed
✅ Configure login/logout pages
✅ Handle access errors
✅ Create initial roles and users
🎯 Next Step
Session-based authentication is perfect for web applications, but for modern REST APIs, JWT is the standard.
➡️ Chapter 3: JWT (JSON Web Tokens)