TP4 - Login Social avec Google OAuth2
Objectifs du TP
Dans ce TP, vous allez:
- ✅ Configurer un projet Google Cloud
- ✅ Intégrer OAuth2 Client avec Spring Security
- ✅ Récupérer les informations utilisateur Google
- ✅ Lier les comptes Google aux utilisateurs locaux
- ✅ Combiner login classique et login social
Durée estimée: 1h30
Prérequis
- Un compte Google
- Accès à Google Cloud Console
- Le projet du TP8.1 (form login)
Partie 1: Configuration Google Cloud
Étape 1: Créer un Projet
- Aller sur https://console.cloud.google.com
- Créer un nouveau projet: "Spring Security Demo"
- Sélectionner ce projet
Étape 2: Configurer OAuth Consent Screen
- Menu → "APIs & Services" → "OAuth consent screen"
- Type: External
- Remplir:
- App name: "Mon App Spring"
- User support email: votre email
- Developer contact: votre email
- Scopes: Ajouter
email,profile,openid - Test users: Ajouter votre email Google
Étape 3: Créer les Credentials
- Menu → "APIs & Services" → "Credentials"
- "Create Credentials" → "OAuth client ID"
- Application type: Web application
- Name: "Spring Boot App"
- Authorized redirect URIs:
http://localhost:8080/login/oauth2/code/google - Copier le Client ID et Client Secret
Partie 2: Configuration Spring Boot
Dépendances
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
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
Partie 3: SecurityConfig
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final CustomUserDetailsService userDetailsService;
private final CustomOAuth2UserService oAuth2UserService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login", "/register", "/error", "/css/**").permitAll()
.anyRequest().authenticated()
)
// Login classique
.formLogin(form -> form
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.permitAll()
)
// Login OAuth2
.oauth2Login(oauth -> oauth
.loginPage("/login")
.userInfoEndpoint(userInfo -> userInfo
.userService(oAuth2UserService)
)
.defaultSuccessUrl("/dashboard")
)
.logout(logout -> logout
.logoutSuccessUrl("/")
.permitAll()
)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Partie 4: CustomOAuth2UserService
@Service
@RequiredArgsConstructor
@Slf4j
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
@Override
@Transactional
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oauth2User = super.loadUser(userRequest);
String provider = userRequest.getClientRegistration().getRegistrationId();
String providerId = oauth2User.getAttribute("sub"); // Google ID
String email = oauth2User.getAttribute("email");
String name = oauth2User.getAttribute("name");
String picture = oauth2User.getAttribute("picture");
log.info("OAuth2 login: provider={}, email={}", provider, email);
// Chercher ou créer l'utilisateur
User user = userRepository.findByEmail(email)
.orElseGet(() -> createOAuth2User(email, name, provider, providerId));
// Mettre à jour les infos OAuth2
user.setOauth2Provider(provider);
user.setOauth2Id(providerId);
user.setProfilePicture(picture);
userRepository.save(user);
return new CustomOAuth2User(oauth2User, user);
}
private User createOAuth2User(String email, String name, String provider, String providerId) {
User user = new User();
user.setEmail(email);
user.setUsername(email); // Utiliser l'email comme username
user.setPassword(""); // Pas de mot de passe pour OAuth2
user.setEnabled(true);
user.setOauth2Provider(provider);
user.setOauth2Id(providerId);
// Extraire prénom/nom si possible
if (name != null) {
String[] parts = name.split(" ", 2);
user.setFirstName(parts[0]);
if (parts.length > 1) {
user.setLastName(parts[1]);
}
}
// Assigner rôle par défaut
Role userRole = roleRepository.findByName("ROLE_USER")
.orElseThrow(() -> new RuntimeException("Role ROLE_USER not found"));
user.getRoles().add(userRole);
return userRepository.save(user);
}
}
Partie 5: 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.toSet());
}
@Override
public String getName() {
return user.getUsername();
}
public User getUser() {
return user;
}
public String getEmail() {
return oauth2User.getAttribute("email");
}
public String getPicture() {
return oauth2User.getAttribute("picture");
}
}
Partie 6: User Entity Mise à Jour
@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;
private String password; // Nullable pour OAuth2
@Column(unique = true, nullable = false)
private String email;
private String firstName;
private String lastName;
private String profilePicture;
// OAuth2 fields
private String oauth2Provider; // google, github, etc.
private String oauth2Id; // ID chez le provider
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<>();
public boolean isOAuth2User() {
return oauth2Provider != null;
}
}
Partie 7: Page de Login
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Connexion</title>
<style>
.login-container { max-width: 400px; margin: 50px auto; padding: 20px; }
.oauth-btn { display: block; padding: 10px; margin: 10px 0; text-align: center;
text-decoration: none; border-radius: 5px; }
.google { background: #db4437; color: white; }
.separator { text-align: center; margin: 20px 0; color: #666; }
.form-group { margin-bottom: 15px; }
input { width: 100%; padding: 10px; margin-top: 5px; }
button { width: 100%; padding: 10px; background: #007bff; color: white;
border: none; cursor: pointer; }
</style>
</head>
<body>
<div class="login-container">
<h1>Connexion</h1>
<div th:if="${param.error}" style="color:red; margin-bottom:15px;">
Identifiants incorrects.
</div>
<div th:if="${param.logout}" style="color:green; margin-bottom:15px;">
Déconnexion réussie.
</div>
<!-- OAuth2 Login -->
<a href="/oauth2/authorization/google" class="oauth-btn google">
🔵 Se connecter avec Google
</a>
<div class="separator">— ou —</div>
<!-- Form Login -->
<form th:action="@{/login}" method="post">
<div class="form-group">
<label>Nom d'utilisateur</label>
<input type="text" name="username" required>
</div>
<div class="form-group">
<label>Mot de passe</label>
<input type="password" name="password" required>
</div>
<button type="submit">Se connecter</button>
</form>
<p style="text-align:center; margin-top:20px;">
<a href="/register">Pas de compte? S'inscrire</a>
</p>
</div>
</body>
</html>
Partie 8: Dashboard avec Info OAuth2
<!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>
<div sec:authorize="isAuthenticated()">
<h2>Bienvenue, <span sec:authentication="name">User</span>!</h2>
<!-- Afficher la photo si OAuth2 -->
<div th:if="${user != null and user.profilePicture != null}">
<img th:src="${user.profilePicture}" alt="Profile"
style="width:50px; height:50px; border-radius:50%;">
</div>
<h3>Informations:</h3>
<ul>
<li>Email: <span th:text="${user.email}">email@test.com</span></li>
<li>Provider: <span th:text="${user.oauth2Provider ?: 'Local'}">-</span></li>
<li>Rôles: <span sec:authentication="authorities">ROLE_USER</span></li>
</ul>
<form th:action="@{/logout}" method="post">
<button type="submit">Déconnexion</button>
</form>
</div>
</body>
</html>
Controller
@Controller
public class DashboardController {
@GetMapping("/dashboard")
public String dashboard(Model model, Authentication authentication) {
if (authentication.getPrincipal() instanceof CustomOAuth2User) {
CustomOAuth2User oAuth2User = (CustomOAuth2User) authentication.getPrincipal();
model.addAttribute("user", oAuth2User.getUser());
} else if (authentication.getPrincipal() instanceof CustomUserDetails) {
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
model.addAttribute("user", userDetails.getUser());
}
return "dashboard";
}
}
Partie 9: Test
Checklist
- Aller sur http://localhost:8080/login
- Cliquer "Se connecter avec Google"
- Redirection vers Google
- Autoriser l'application
- Redirection vers /dashboard
- Voir les infos Google (email, photo)
- Vérifier en BDD: utilisateur créé avec oauth2_provider="google"
- Se déconnecter
- Se reconnecter avec Google → même utilisateur
- Se connecter avec login/password classique → fonctionne aussi
Vérification H2
SELECT id, username, email, oauth2_provider, oauth2_id
FROM users;
Bonus: Lier un Compte Google à un Compte Existant
Endpoint pour Lier
@PostMapping("/link/google")
@PreAuthorize("isAuthenticated()")
public String linkGoogle(@AuthenticationPrincipal CustomUserDetails currentUser) {
// Rediriger vers OAuth2 Google avec un state spécial
return "redirect:/oauth2/authorization/google?link=true";
}
Handler de Succès Personnalisé
@Component
public class OAuth2SuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException {
// Vérifier si c'est un linking
if (request.getParameter("link") != null) {
// Lier au compte existant
// ...
}
super.onAuthenticationSuccess(request, response, authentication);
}
}
Résumé
Flow OAuth2 avec Google
1. Clic "Login with Google"
2. Redirection: /oauth2/authorization/google
3. Google: Login + Consent
4. Callback: /login/oauth2/code/google?code=XXX
5. Spring: Échange code → tokens
6. CustomOAuth2UserService: Crée/trouve l'utilisateur
7. Dashboard: Connecté!
Points Clés
spring-boot-starter-oauth2-clientgère tout le flowCustomOAuth2UserServicepour personnaliser la création d'utilisateur- Un utilisateur peut avoir un compte local ET OAuth2
- Les infos Google (photo, nom) peuvent être stockées localement
🎯 Module Terminé!
Félicitations! Vous avez complété le Module 8 - Spring Security.
Récapitulatif:
- Chapitre 1: Architecture Spring Security
- Chapitre 2: Form Login et HTTP Basic
- Chapitre 3: JWT Authentication
- Chapitre 4: OAuth2 et Login Social
- Chapitre 5: Sécurité Avancée (CSRF, CORS, @PreAuthorize)
- TP8.1: Form Login
- TP8.2: API REST avec JWT
- TP8.3: Rôles et Permissions
- TP8.4: OAuth2 Google (ce TP)