'Spring Security - SAML 2.0: Get the current username(email) when the authentication fails

I have a saml configuration and I want to get the username(email) that is doing the login in my CustomSimpleUrlAuthenticationFailureHandler.java. The companyMetadataProvider has the providers registered. I have this:

private void sendEmailSamlNotification(HttpServletRequest request,
        HttpServletResponse response, AuthenticationException exception) {
    try {
        SAMLMessageContext context = contextProvider.getLocalEntity(request, response);
        SAMLAuthenticationToken token = new SAMLAuthenticationToken(context);
        SAMLMessageContext credentials = token.getCredentials();
        CompanySpecificMetaDataProvider companyMetadataProvider = (CompanySpecificMetaDataProvider) context.getMetadataProvider();
        logger.info("Data comany domain"+companyMetadataProvider.getEmailDomain());
        if(java.util.Objects.nonNull(companyMetadataProvider)) {
            // here I send an email
        }else {
            logger.info("Status SAML : Metadata not found in sendEmailSamlNotification");
        }
    } catch (MetadataProviderException e) {
        e.printStackTrace();
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source