TP1 - Authentication via Form
Objectives of the TP
In this TP, you will:
- ✅ Create a secure web application with Spring Security
- ✅ Implement form-based authentication
- ✅ Store users in a database
- ✅ Manage USER and ADMIN roles
- ✅ Customize login/logout pages
Estimated duration: 1h30
Context
You are creating a task management application with:
- Public homepage
- Dashboard accessible to logged-in users
- Administration page reserved for admins
Part 1: Project Setup
1.1 Create the Project
Spring Initializr with:
- Artifact:
security-form-demo - Dependencies:
- Spring Web
- Spring Security
- Spring Data JPA
- H2 Database
- Thymeleaf
- Lombok
1.2 Structure
src/main/java/com/example/security/
├── config/
│ └── SecurityConfig.java
├── model/
│ ├── User.java
│ └── Role.java
├── repository/
│ ├── UserRepository.java
│ └── RoleRepository.java
├── service/
│ ├── CustomUserDetailsService.java
│ └── UserService.java
├── controller/
│ ├── HomeController.java
│ └── AdminController.java
└── SecurityFormDemoApplication.java
Part 2: Entities
2.1 Role
@Entity
@Table(name = "roles")
@Data
@NoArgsConstructor
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String name;
public Role(String name) {
this.name = name;
}
}
2.2 User
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
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<>();
}
Part 3: Repositories and Services
3.1 Repositories
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
boolean existsByUsername(String username);
}
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(String name);
}
3.2 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 org.springframework.security.core.userdetails.User.builder()
.username(user.getUsername())
.password(user.getPassword())
.authorities(user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.toList())
.disabled(!user.isEnabled())
.build();
}
}
3.3 UserService
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
private final PasswordEncoder passwordEncoder;
@Transactional
public User createUser(String username, String email, String password, String roleName) {
if (userRepository.existsByUsername(username)) {
throw new RuntimeException("Username already taken");
}
Role role = roleRepository.findByName(roleName)
.orElseThrow(() -> new RuntimeException("Role not found: " + roleName));
User user = new User();
user.setUsername(username);
user.setEmail(email);
user.setPassword(passwordEncoder.encode(password));
user.setEnabled(true);
user.getRoles().add(role);
return userRepository.save(user);
}
}
Part 4: Security Configuration
4.1 SecurityConfig
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final CustomUserDetailsService userDetailsService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/home", "/register", "/css/**", "/js/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.defaultSuccessUrl("/dashboard", true)
.failureUrl("/login?error=true")
.permitAll()
)
.logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout=true")
.deleteCookies("JSESSIONID")
.permitAll()
)
.userDetailsService(userDetailsService)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Part 5: Controllers
5.1 HomeController
@Controller
public class HomeController {
@GetMapping({"/", "/home"})
public String home() {
return "home";
}
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/dashboard")
public String dashboard(Model model, Principal principal) {
model.addAttribute("username", principal.getName());
return "dashboard";
}
@GetMapping("/register")
public String registerForm(Model model) {
model.addAttribute("user", new User());
return "register";
}
@PostMapping("/register")
public String register(@ModelAttribute User user,
@RequestParam String password,
RedirectAttributes redirectAttributes,
UserService userService) {
try {
userService.createUser(user.getUsername(), user.getEmail(), password, "ROLE_USER");
redirectAttributes.addFlashAttribute("success", "Account created! Please log in.");
return "redirect:/login";
} catch (Exception e) {
redirectAttributes.addFlashAttribute("error", e.getMessage());
return "redirect:/register";
}
}
}
5.2 AdminController
@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {
private final UserRepository userRepository;
@GetMapping
public String adminDashboard(Model model) {
model.addAttribute("users", userRepository.findAll());
return "admin/dashboard";
}
@PostMapping("/users/{id}/disable")
public String disableUser(@PathVariable Long id) {
userRepository.findById(id).ifPresent(user -> {
user.setEnabled(false);
userRepository.save(user);
});
return "redirect:/admin";
}
}
Part 6: Thymeleaf Templates
6.1 home.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome!</h1>
<div sec:authorize="isAnonymous()">
<p>You are not logged in.</p>
<a href="/login">Login</a> | <a href="/register">Register</a>
</div>
<div sec:authorize="isAuthenticated()">
<p>Hello, <span sec:authentication="name">User</span>!</p>
<a href="/dashboard">Dashboard</a>
<div sec:authorize="hasRole('ADMIN')">
<a href="/admin">Administration</a>
</div>
<form th:action="@{/logout}" method="post" style="display:inline;">
<button type="submit">Logout</button>
</form>
</div>
</body>
</html>
6.2 login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<div th:if="${param.error}" style="color:red;">
Incorrect username or password.
</div>
<div th:if="${param.logout}" style="color:green;">
Successfully logged out.
</div>
<div th:if="${success}" style="color:green;" th:text="${success}"></div>
<form th:action="@{/login}" method="post">
<div>
<label>Username:</label>
<input type="text" name="username" required/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password" required/>
</div>
<button type="submit">Login</button>
</form>
<p><a href="/register">No account? Register</a></p>
</body>
</html>
6.3 dashboard.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<title>Dashboard</title>
</head>
<body>
<h1>Dashboard</h1>
<p>Welcome, <span th:text="${username}">User</span>!</p>
<h2>Your roles:</h2>
<ul sec:authentication="authorities">
<!-- Display roles -->
</ul>
<a href="/home">Home</a>
<form th:action="@{/logout}" method="post" style="display:inline;">
<button type="submit">Logout</button>
</form>
</body>
</html>
Part 7: Initial Data
DataInitializer
@Component
@RequiredArgsConstructor
public class DataInitializer implements CommandLineRunner {
private final RoleRepository roleRepository;
private final UserService userService;
@Override
@Transactional
public void run(String... args) {
// Create roles
if (roleRepository.count() == 0) {
roleRepository.save(new Role("ROLE_USER"));
roleRepository.save(new Role("ROLE_ADMIN"));
}
// Create a default admin
try {
userService.createUser("admin", "admin@test.com", "admin123", "ROLE_ADMIN");
userService.createUser("user", "user@test.com", "user123", "ROLE_USER");
} catch (Exception ignored) {}
}
}
Part 8: Configuration
# application.properties
spring.datasource.url=jdbc:h2:mem:securitydb
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
logging.level.org.springframework.security=DEBUG
Tests
Checklist
- Homepage accessible to all
- Login with user/user123 → Dashboard
- Login with admin/admin123 → Dashboard + Admin access
- User cannot access /admin (403)
- Logout works
- Registration creates a new user
Manual Tests
1. http://localhost:8080 → Homepage
2. Click "Login" → Login page
3. Login admin/admin123 → Dashboard
4. Access /admin → OK
5. Logout → Back to login
6. Login user/user123 → Dashboard
7. Access /admin → 403 Forbidden