Java/Spring Boot Security

Spring boot Security redirect after logging

바리새인 2024. 7. 29. 22:42

원하는 redirect로 가도록 successHandler 설정

@Component
public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
	   @Override
	    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
	                                        Authentication authentication) throws IOException {
	        // Custom logic after successful authentication
	        // For example, redirecting to a specific URL based on user roles

	        String redirectUrl = determineTargetUrl(authentication);
	        if (response.isCommitted()) {
	            return;
	        }
	        getRedirectStrategy().sendRedirect(request, response, redirectUrl);
	    }

		// 원하는 URL로 변경하는 로직 적용
	    protected String determineTargetUrl(Authentication authentication) {
	        // Determine the URL to redirect to based on user roles or other logic
	        return "/home"; // Default redirect URL after successful login
	    }
}


public class WebSecurityConfig {
    String[] exceptUrl = {
    	"/"
    }
    
    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
    
	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http.authorizeHttpRequests((requests) -> requests
				.requestMatchers(exceptUrl).permitAll()
				.anyRequest().authenticated())
			.formLogin((form) -> form
				.loginPage("/login")
				.successHandler(customAuthenticationSuccessHandler)
				.permitAll())
			.logout((logout) -> logout.permitAll());
		return http.build();
	}

원래 redirect로 가도록 successHandler 설정

@Component
public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	private RequestCache requestCache = new HttpSessionRequestCache();	
	
	@Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
		SavedRequest savedRequest = requestCache.getRequest(request, response);
        // Custom logic after successful authentication
        // For example, redirecting to a specific URL based on user roles

	   /*
	   String redirectUrl = determineTargetUrl(authentication);
       if (response.isCommitted()) {
    	   return;
       }
       getRedirectStrategy().sendRedirect(request, response, redirectUrl);
       */
	   
		if (savedRequest == null) {
			// No saved request, use default target URL
			super.onAuthenticationSuccess(request, response, authentication);
			return;
        }

		// Get the original URL the user was trying to access
		String targetUrl = savedRequest.getRedirectUrl();
		System.out.println("Original redirect URL: " + targetUrl);

		// Clear the saved request from the session
		requestCache.removeRequest(request, response);
        
		// Proceed with the redirect
		getRedirectStrategy().sendRedirect(request, response, targetUrl);		   
    }
}