Skip to main content

TP4 - Social Login with Google OAuth2

Objectives of the TP​

In this TP, you will:

  1. ✅ Configure a Google Cloud project
  2. ✅ Integrate OAuth2 Client with Spring Security
  3. ✅ Retrieve Google user information
  4. ✅ Link Google accounts to local users
  5. ✅ Combine classic login and social login

Estimated duration: 1h30


Prerequisites​

  • A Google account
  • Access to Google Cloud Console
  • The project from TP8.1 (form login)

Part 1: Google Cloud Configuration​

Step 1: Create a Project​

  1. Go to https://console.cloud.google.com
  2. Create a new project: "Spring Security Demo"
  3. Select this project
  1. Menu → "APIs & Services" → "OAuth consent screen"
  2. Type: External
  3. Fill in:
    • App name: "My Spring App"
    • User support email: your email
    • Developer contact: your email
  4. Scopes: Add email, profile, openid
  5. Test users: Add your Google email

Step 3: Create the Credentials​

  1. Menu → "APIs & Services" → "Credentials"
  2. "Create Credentials" → "OAuth client ID"
  3. Application type: Web application
  4. Name: "Spring Boot App"
  5. Authorized redirect URIs:
    http://localhost:8080/login/oauth2/code/google
  6. Copy the Client ID and Client Secret

Part 2: Spring Boot Configuration​

Dependencies​

<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=YOUR_CLIENT_ID
spring.security.oauth2.client.registration.google.client-secret=YOUR_CLIENT_SECRET
spring.security.oauth2.client.registration.google.scope=openid,profile,email

Part 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()
)
// Classic login
.formLogin(form -> form
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.permitAll()
)
// OAuth2 Login
.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();
}
}

Part 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);

// Find or create the user
User user = userRepository.findByEmail(email)
.orElseGet(() -> createOAuth2User(email, name, provider, providerId));

// Update OAuth2 info
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); // Use email as username
user.setPassword(""); // No password for OAuth2
user.setEnabled(true);
user.setOauth2Provider(provider);
user.setOauth2Id(providerId);

// Extract first/last name if possible
if (name != null) {
String[] parts = name.split(" ", 2);
user.setFirstName(parts[0]);
if (parts.length > 1) {
user.setLastName(parts[1]);
}
}

// Assign default role
Role userRole = roleRepository.findByName("ROLE_USER")
.orElseThrow(() -> new RuntimeException("Role ROLE_USER not found"));
user.getRoles().add(userRole);

return userRepository.save(user);
}
}

Part 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");
}
}

Part 6: User Entity Update​

@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 for 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 at the 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;
}
}

Part 7: Login Page​

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</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>Login</h1>

<div th:if="${param.error}" style="color:red; margin-bottom:15px;">
Incorrect credentials.
</div>
<div th:if="${param.logout}" style="color:green; margin-bottom:15px;">
Successfully logged out.
</div>

<!-- OAuth2 Login -->
<a href="/oauth2/authorization/google" class="oauth-btn google">
🔵 Sign in with Google
</a>

<div class="separator">— or —</div>

<!-- Form Login -->
<form th:action="@{/login}" method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="username" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" required>
</div>
<button type="submit">Sign in</button>
</form>

<p style="text-align:center; margin-top:20px;">
<a href="/register">No account? Register</a>
</p>
</div>
</body>
</html>

Part 8: Dashboard with OAuth2 Info​

<!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>Welcome, <span sec:authentication="name">User</span>!</h2>

<!-- Display photo if 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>Information:</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>Roles: <span sec:authentication="authorities">ROLE_USER</span></li>
</ul>

<form th:action="@{/logout}" method="post">
<button type="submit">Logout</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";
}
}

Part 9: Test​

Checklist​

  1. Go to http://localhost:8080/login
  2. Click "Sign in with Google"
  3. Redirect to Google
  4. Authorize the application
  5. Redirect to /dashboard
  6. See Google info (email, photo)
  7. Check in DB: user created with oauth2_provider="google"
  8. Log out
  9. Log back in with Google → same user
  10. Log in with classic login/password → also works

H2 Verification​

SELECT id, username, email, oauth2_provider, oauth2_id 
FROM users;

@PostMapping("/link/google")
@PreAuthorize("isAuthenticated()")
public String linkGoogle(@AuthenticationPrincipal CustomUserDetails currentUser) {
// Redirect to Google OAuth2 with a special state
return "redirect:/oauth2/authorization/google?link=true";
}

Custom Success Handler​

@Component
public class OAuth2SuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException {
// Check if it's a linking
if (request.getParameter("link") != null) {
// Link to existing account
// ...
}

super.onAuthenticationSuccess(request, response, authentication);
}
}

Summary​

OAuth2 Flow with Google​

1. Click "Login with Google"
2. Redirect: /oauth2/authorization/google
3. Google: Login + Consent
4. Callback: /login/oauth2/code/google?code=XXX
5. Spring: Exchange code → tokens
6. CustomOAuth2UserService: Create/find the user
7. Dashboard: Connected!

Key Points​

  • spring-boot-starter-oauth2-client handles the entire flow
  • CustomOAuth2UserService to customize user creation
  • A user can have both a local and an OAuth2 account
  • Google info (photo, name) can be stored locally

🎯 Module Completed!​

Congratulations! You have completed Module 8 - Spring Security.

Recap:

  • Chapter 1: Spring Security Architecture
  • Chapter 2: Form Login and HTTP Basic
  • Chapter 3: JWT Authentication
  • Chapter 4: OAuth2 and Social Login
  • Chapter 5: Advanced Security (CSRF, CORS, @PreAuthorize)
  • TP8.1: Form Login
  • TP8.2: REST API with JWT
  • TP8.3: Roles and Permissions
  • TP8.4: Google OAuth2 (this TP)

➡️ Back to Module 8


⬅️ Back to Course Plan