package net.gepafin.tendermanagement.config; import java.io.IOException; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import net.gepafin.tendermanagement.entities.SamlResponseLogEntity; import net.gepafin.tendermanagement.repositories.SamlResponseLogRepository; @Component public class SamlSuccessHandler implements AuthenticationSuccessHandler{ private final Logger logger = LoggerFactory.getLogger(SamlSuccessHandler.class); @Autowired private SamlResponseLogRepository samlResponseLogRepository; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { try { // Cast the authentication object to Saml2Authentication Saml2Authentication samlAuth = (Saml2Authentication) authentication; Saml2AuthenticatedPrincipal principal = (Saml2AuthenticatedPrincipal) samlAuth.getPrincipal(); // Extract the user attributes from the principal Map> userAttributes = principal.getAttributes(); // Log the user attributes for debugging purposes logger.info("SAML User Attributes: " + userAttributes); // Save the authentication details in the database (Optional) SamlResponseLogEntity samlResponseLogEntity = new SamlResponseLogEntity(); samlResponseLogEntity.setAuthenticationObject(authentication.toString()); // Convert user attributes to JSON and save in DB ObjectMapper objectMapper = new ObjectMapper(); String userAttributesJson = objectMapper.writeValueAsString(userAttributes); samlResponseLogEntity.setAuthenticationObject(userAttributesJson); samlResponseLogRepository.save(samlResponseLogEntity); // Successful login logic logger.info("SAML login successful for user: " + principal.getName()); response.sendRedirect("http://gepafin-staging-fe.s3-website.eu-central-1.amazonaws.com/login"); } catch (Exception e) { logger.error("Error processing SAML success handler", e); } } }