Chapitre 4: OAuth2 et Login Social
Introduction
Au lieu de gérer les mots de passe vous-même, pourquoi ne pas laisser Google, GitHub ou Facebook s'en charger? OAuth2 permet à vos utilisateurs de se connecter avec leurs comptes existants, améliorant ainsi l'UX et la sécurité.
🎯 Objectifs du Chapitre
À la fin de ce chapitre, vous saurez:
- ✅ Comprendre OAuth2 et ses concepts
- ✅ Distinguer les différents flows OAuth2
- ✅ Configurer Spring Security OAuth2 Client
- ✅ Implémenter le login Google
- ✅ Récupérer les informations utilisateur
1. Concepts OAuth2
Les 4 Rôles
| Rôle | Description | Exemple |
|---|---|---|
| Resource Owner | L'utilisateur qui possède les données | Jean qui veut se connecter |
| Client | Votre application | votre-app.com |
| Authorization Server | Serveur qui authentifie | accounts.google.com |
| Resource Server | Serveur qui a les données | googleapis.com |
Authorization Code Flow
Le flow le plus sécurisé pour les applications web:
2. Configuration Spring Boot
Dépendances
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
Configuration Google
Étape 1: Créer un Projet Google Cloud
- Aller sur https://console.cloud.google.com
- Créer un nouveau projet
- Aller dans "APIs & Services" → "Credentials"
- Créer "OAuth 2.0 Client IDs"
- Type: "Web application"
- Authorized redirect URIs:
http://localhost:8080/login/oauth2/code/google
Étape 2: application.properties
# Google OAuth2
spring.security.oauth2.client.registration.google.client-id=VOTRE_CLIENT_ID
spring.security.oauth2.client.registration.google.client-secret=VOTRE_CLIENT_SECRET
spring.security.oauth2.client.registration.google.scope=openid,profile,email
Configuration GitHub
Étape 1: GitHub Developer Settings
- Aller sur https://github.com/settings/developers
- "OAuth Apps" → "New OAuth App"
- Homepage URL:
http://localhost:8080 - Authorization callback URL:
http://localhost:8080/login/oauth2/code/github
Étape 2: application.properties
# GitHub OAuth2
spring.security.oauth2.client.registration.github.client-id=VOTRE_CLIENT_ID
spring.security.oauth2.client.registration.github.client-secret=VOTRE_CLIENT_SECRET
spring.security.oauth2.client.registration.github.scope=user:email
3. SecurityConfig pour OAuth2
Configuration de Base
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login", "/error", "/css/**", "/js/**").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth -> oauth
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
)
.logout(logout -> logout
.logoutSuccessUrl("/")
)
.build();
}
}
Page de Login avec Boutons OAuth2
<!-- templates/login.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Connexion</title>
<style>
.oauth-buttons { margin-top: 20px; }
.oauth-btn {
display: inline-block;
padding: 10px 20px;
margin: 5px;
border-radius: 5px;
text-decoration: none;
color: white;
}
.google { background: #db4437; }
.github { background: #333; }
</style>
</head>
<body>
<div class="login-container">
<h1>Connexion</h1>
<!-- Login classique -->
<form th:action="@{/login}" method="post">
<input type="text" name="username" placeholder="Nom d'utilisateur">
<input type="password" name="password" placeholder="Mot de passe">
<button type="submit">Se connecter</button>
</form>
<hr>
<!-- Login OAuth2 -->
<div class="oauth-buttons">
<p>Ou connectez-vous avec:</p>
<a href="/oauth2/authorization/google" class="oauth-btn google">
🔵 Google
</a>
<a href="/oauth2/authorization/github" class="oauth-btn github">
⚫ GitHub
</a>
</div>
</div>
</body>
</html>
4. Récupérer les Informations Utilisateur
Dans un Controller
@Controller
public class ProfileController {
@GetMapping("/dashboard")
public String dashboard(
@AuthenticationPrincipal OAuth2User oauth2User,
Model model) {
if (oauth2User != null) {
model.addAttribute("name", oauth2User.getAttribute("name"));
model.addAttribute("email", oauth2User.getAttribute("email"));
model.addAttribute("picture", oauth2User.getAttribute("picture"));
model.addAttribute("attributes", oauth2User.getAttributes());
}
return "dashboard";
}
}
Attributs par Provider
Google
oauth2User.getAttribute("sub"); // ID unique
oauth2User.getAttribute("name"); // Nom complet
oauth2User.getAttribute("email"); // Email
oauth2User.getAttribute("picture"); // URL de la photo
GitHub
oauth2User.getAttribute("id"); // ID unique
oauth2User.getAttribute("login"); // Username
oauth2User.getAttribute("name"); // Nom complet
oauth2User.getAttribute("email"); // Email (peut être null)
oauth2User.getAttribute("avatar_url"); // URL de l'avatar
5. Lier OAuth2 à Vos Utilisateurs
Stratégie
Entité OAuth2Connection
@Entity
@Table(name = "oauth2_connections")
@Data
@NoArgsConstructor
public class OAuth2Connection {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(nullable = false)
private String provider; // google, github
@Column(nullable = false)
private String providerUserId; // ID chez le provider
@Column(nullable = false)
private LocalDateTime connectedAt = LocalDateTime.now();
}
CustomOAuth2UserService
@Service
@RequiredArgsConstructor
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private final UserRepository userRepository;
private final OAuth2ConnectionRepository connectionRepository;
@Override
@Transactional
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oauth2User = super.loadUser(userRequest);
String provider = userRequest.getClientRegistration().getRegistrationId();
String providerUserId = getProviderUserId(oauth2User, provider);
String email = oauth2User.getAttribute("email");
String name = oauth2User.getAttribute("name");
// Chercher une connexion existante
Optional<OAuth2Connection> existingConnection = connectionRepository
.findByProviderAndProviderUserId(provider, providerUserId);
User user;
if (existingConnection.isPresent()) {
user = existingConnection.get().getUser();
} else if (email != null && userRepository.existsByEmail(email)) {
// Lier à un compte existant par email
user = userRepository.findByEmail(email).orElseThrow();
createConnection(user, provider, providerUserId);
} else {
// Créer un nouveau compte
user = createNewUser(email, name);
createConnection(user, provider, providerUserId);
}
return new CustomOAuth2User(oauth2User, user);
}
private String getProviderUserId(OAuth2User oauth2User, String provider) {
return switch (provider) {
case "google" -> oauth2User.getAttribute("sub");
case "github" -> String.valueOf(oauth2User.getAttribute("id"));
default -> throw new OAuth2AuthenticationException("Provider non supporté");
};
}
private User createNewUser(String email, String name) {
User user = new User();
user.setEmail(email);
user.setUsername(email); // Ou générer un username
user.setPassword(""); // Pas de mot de passe pour OAuth2
user.setEnabled(true);
// Ajouter rôle par défaut
return userRepository.save(user);
}
private void createConnection(User user, String provider, String providerUserId) {
OAuth2Connection connection = new OAuth2Connection();
connection.setUser(user);
connection.setProvider(provider);
connection.setProviderUserId(providerUserId);
connectionRepository.save(connection);
}
}
CustomOAuth2User
public class CustomOAuth2User implements OAuth2User {
private final OAuth2User oauth2User;
private final User user;
public CustomOAuth2User(OAuth2User oauth2User, User user) {
this.oauth2User = oauth2User;
this.user = user;
}
@Override
public Map<String, Object> getAttributes() {
return oauth2User.getAttributes();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
@Override
public String getName() {
return user.getUsername();
}
public User getUser() {
return user;
}
}
Configuration avec Custom Service
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final CustomOAuth2UserService customOAuth2UserService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login", "/error").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth -> oauth
.loginPage("/login")
.userInfoEndpoint(userInfo -> userInfo
.userService(customOAuth2UserService)
)
.defaultSuccessUrl("/dashboard")
)
.build();
}
}
6. Combiner OAuth2 + Form Login
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login", "/register", "/error").permitAll()
.anyRequest().authenticated()
)
// Login par formulaire
.formLogin(form -> form
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.permitAll()
)
// Login OAuth2
.oauth2Login(oauth -> oauth
.loginPage("/login")
.userInfoEndpoint(userInfo -> userInfo
.userService(customOAuth2UserService)
)
.defaultSuccessUrl("/dashboard")
)
.logout(logout -> logout.permitAll())
.build();
}
7. OAuth2 pour API REST (JWT + OAuth2)
Flow Hybride
Endpoint pour Échange Token
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class OAuth2TokenController {
private final GoogleIdTokenVerifier verifier;
private final UserService userService;
private final JwtService jwtService;
@PostMapping("/google")
public ResponseEntity<AuthResponse> googleAuth(@RequestBody GoogleAuthRequest request) {
try {
// Valider le token Google
GoogleIdToken idToken = verifier.verify(request.getIdToken());
if (idToken == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
GoogleIdToken.Payload payload = idToken.getPayload();
String email = payload.getEmail();
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
// Créer ou trouver l'utilisateur
User user = userService.findOrCreateGoogleUser(email, name, pictureUrl);
// Générer JWT
UserDetails userDetails = new CustomUserDetails(user);
String accessToken = jwtService.generateToken(userDetails);
String refreshToken = jwtService.generateRefreshToken(userDetails);
return ResponseEntity.ok(AuthResponse.builder()
.accessToken(accessToken)
.refreshToken(refreshToken)
.username(user.getUsername())
.build());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
}
8. Résumé
Concepts Clés
| Terme | Description |
|---|---|
| OAuth2 | Protocole d'autorisation |
| Authorization Code | Flow pour apps web |
| Access Token | Accès aux ressources |
| ID Token | Identité de l'utilisateur (OpenID Connect) |
Configuration Minimale
spring.security.oauth2.client.registration.google.client-id=XXX
spring.security.oauth2.client.registration.google.client-secret=YYY
Liens de Login
/oauth2/authorization/google → Login Google
/oauth2/authorization/github → Login GitHub
🎯 Prochaine Étape
Maintenant que vous maîtrisez l'authentification, passons aux fonctionnalités de sécurité avancée (CSRF, CORS, @PreAuthorize).
➡️ Chapitre 5: Sécurité Avancée