0Pricing
Spring Security 6 & JWT Authentication · Ders

Özel OAuth2 başarı işleyicisi

Başarılı bir OAuth2 kimlik doğrulamasından sonra kullanıcı bilgilerini işlemek için özel bir başarı işleyicisi geliştirin.

Özel OAuth2 başarı işleyicisi, CoddyKit'te ücretsiz bir Spring Security 6 & JWT Authentication dersidir. Bu, 4 dersinin 3. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Spring Security 6 & JWT Authentication öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Spring Security 6 & JWT Authentication kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Intro to OAuth2 Success Handlers

Welcome to our lesson on custom OAuth2 success handlers! After a user successfully logs in via an OAuth2 provider (like Google or GitHub), Spring Security needs to know what to do next.

By default, it handles basic redirection. But what if you need to perform custom actions, like saving user details or updating their profile? That's where custom success handlers come in!

Default OAuth2 Success Flow

When a user successfully authenticates with an OAuth2 provider, Spring Security's default behavior is quite straightforward:

  • It extracts user details (like name, email) from the provider's response.
  • It creates an OAuth2AuthenticationToken.
  • It redirects the user to the application's root URL (or a previously requested URL).

This is often enough for simple integrations, but real-world apps usually need more.

Why Customize Success Handling?

Customizing the success handler allows you to:

  • Store User Data: Save new users or update existing ones in your application's database.
  • Generate Tokens: Create custom session tokens or JWTs after OAuth2 login.
  • Redirect Dynamically: Send users to different pages based on their role or status.
  • Logging & Auditing: Log successful logins for security monitoring.

It gives you fine-grained control over the post-authentication process.

The AuthenticationSuccessHandler

Spring Security provides the AuthenticationSuccessHandler interface. You implement this interface to define custom logic for successful authentication events.

Its core method is onAuthenticationSuccess, which gets called after authentication passes.

public interface AuthenticationSuccessHandler {
void onAuthenticationSuccess(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication
) throws IOException, ServletException;
}

Building a Simple Custom Handler

Let's create a basic custom handler that just logs the successful authentication and then redirects. We'll implement the AuthenticationSuccessHandler interface.

import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.core.Authentication;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class CustomOAuth2SuccessHandler implements AuthenticationSuccessHandler {

    private static final Logger logger = LoggerFactory.getLogger(CustomOAuth2SuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(
        HttpServletRequest request,
        HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

        logger.info("OAuth2 login successful for user: " + authentication.getName());
        // Default redirect to home page
        response.sendRedirect("/");
    }
}

Configuring the Custom Handler

To make Spring Security use our custom handler, we need to configure it in our SecurityFilterChain bean. We'll use the oauth2Login() method.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final AuthenticationSuccessHandler customOAuth2SuccessHandler;

    public SecurityConfig(AuthenticationSuccessHandler customOAuth2SuccessHandler) {
        this.customOAuth2SuccessHandler = customOAuth2SuccessHandler;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .oauth2Login(oauth2 -> oauth2
                .successHandler(customOAuth2SuccessHandler) // <--- Register our handler
            );
        return http.build();
    }
}

Accessing User Details

Inside onAuthenticationSuccess, the Authentication object holds the authenticated principal. For OAuth2, this principal will be an OAuth2User.

You can cast it to OAuth2User to access provider-specific attributes like email, name, or unique IDs (e.g., Google ID).

import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;

// Inside onAuthenticationSuccess method:

public void onAuthenticationSuccess(
    HttpServletRequest request,
    HttpServletResponse response,
    Authentication authentication) throws IOException, ServletException {

    if (authentication instanceof OAuth2AuthenticationToken) {
        OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
        OAuth2User oauth2User = oauthToken.getPrincipal();

        String email = oauth2User.getAttribute("email");
        String name = oauth2User.getAttribute("name");
        String provider = oauthToken.getAuthorizedClientRegistrationId();

        logger.info("User logged in: " + name + " from " + provider + " with email: " + email);
        // ... further processing
    }
    response.sendRedirect("/");
}

Practical: Saving User to DB

A common use case is to save or update user information in your database after a successful OAuth2 login. Here's a simplified example:

import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// Assume you have a UserService and User entity
// public interface UserService { User saveOrUpdateUser(OAuth2User oauth2User, String provider); }
// public class User { private String email; private String name; /*...*/ }

@Component
public class DatabaseOAuth2SuccessHandler implements AuthenticationSuccessHandler {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseOAuth2SuccessHandler.class);
    // private final UserService userService; // Inject your user service

    // public DatabaseOAuth2SuccessHandler(UserService userService) {
    //     this.userService = userService;
    // }

    @Override
    public void onAuthenticationSuccess(
        HttpServletRequest request,
        HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

        if (authentication instanceof OAuth2AuthenticationToken) {
            OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
            OAuth2User oauth2User = oauthToken.getPrincipal();
            String provider = oauthToken.getAuthorizedClientRegistrationId();

            logger.info("Processing OAuth2 user from " + provider);
            // User savedUser = userService.saveOrUpdateUser(oauth2User, provider);
            // logger.info("User saved/updated: " + savedUser.getEmail());
        }
        response.sendRedirect("/");
    }
}

Custom Redirection Logic

The onAuthenticationSuccess method also allows you to control the redirection after login. You can redirect users to a specific dashboard, a profile setup page, or back to the page they were trying to access.

You can use response.sendRedirect("/some-path") or integrate with Spring's RedirectStrategy.

  • request.getRequestURI(): Get the original request URI.
  • response.sendRedirect("/"): Redirect to the root.
  • new DefaultRedirectStrategy().sendRedirect(request, response, "/dashboard"): More robust redirection.

Quick Check: Success Handlers

Which of the following are valid reasons to implement a custom AuthenticationSuccessHandler for OAuth2 in Spring Security?

Recap: Custom Success Handlers

In this lesson, we explored how to customize the post-authentication process for OAuth2 logins using Spring Security's AuthenticationSuccessHandler.

  • We learned its purpose: extending default behavior for user management, redirection, and auditing.
  • We saw how to implement the onAuthenticationSuccess method.
  • We configured our custom handler in the SecurityFilterChain.
  • We understood how to access OAuth2User details and perform actions like saving users to a database.

Custom success handlers provide powerful control over your application's user experience and data integration after an OAuth2 login.

Sıkça Sorulan Sorular

“Özel OAuth2 başarı işleyicisi” dersi ücretsiz mi?

Evet — “Özel OAuth2 başarı işleyicisi” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Spring Security 6 & JWT Authentication kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Spring Security 6 & JWT Authentication kursu toplamda 4 dersten oluşur.

“Özel OAuth2 başarı işleyicisi” dersinde ne öğreneceğim?

Başarılı bir OAuth2 kimlik doğrulamasından sonra kullanıcı bilgilerini işlemek için özel bir başarı işleyicisi geliştirin. Spring Security 6 & JWT Authentication ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Spring Security 6 & JWT Authentication öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Spring Security 6 & JWT Authentication, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 3. dersidir.

“Özel OAuth2 başarı işleyicisi” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Spring Security 6 & JWT Authentication dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Spring Security 6 & JWT Authentication dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. OAuth2 istemci kurulumu
  2. Sosyal giriş entegrasyonu
  3. Özel OAuth2 başarı işleyicisi
  4. Kimliği Doğrulanmış OAuth2 Kullanıcısına Erişme
← Spring Security 6 & JWT Authentication Sayfasına Dön