Search in sources :

Example 11 with SAMLException

use of org.opensaml.common.SAMLException in project cool-jconon by consiglionazionaledellericerche.

the class SPIDIntegrationService method validateAssertion.

private void validateAssertion(Response response, SPIDRequest spidRequest) throws SAMLException {
    if (response.getAssertions().size() != 1) {
        throw new SAMLException("The response doesn't contain exactly 1 assertion");
    }
    Assertion assertion = response.getAssertions().stream().findFirst().orElseThrow(() -> new SAMLException("The response doesn't contain exactly 1 assertion"));
    Optional.ofNullable(assertion.getSubject()).orElseThrow(() -> new SAMLException("Assertion :: Subject not specified!"));
    Optional.ofNullable(assertion.getSubject().getNameID()).orElseThrow(() -> new SAMLException("Assertion :: The NameID value is missing from the SAML response; this is likely an IDP configuration issue!"));
    final String assertionId = Optional.ofNullable(assertion.getID()).filter(s -> s.length() > 0).orElseThrow(() -> new SAMLException("Assertion :: ID not specified!"));
    final SAMLVersion samlVersion = Optional.ofNullable(assertion.getVersion()).orElseThrow(() -> new SAMLException("Assertion :: Version not specified!"));
    if (samlVersion.getMajorVersion() != 2 || samlVersion.getMinorVersion() != 0) {
        throw new SAMLException("Assertion :: Version is not correct!");
    }
    final DateTime issueInstant = Optional.ofNullable(assertion.getIssueInstant()).orElseThrow(() -> new SAMLException("Assertion :: IssueInstant not specified!"));
    if (!spidRequest.getIssueIstant().isBefore(issueInstant)) {
        throw new SAMLException("Assertion :: IssueInstant is before " + spidRequest.getIssueIstant().toString());
    }
    final AuthnStatement authnStatement = assertion.getAuthnStatements().stream().findAny().orElseThrow(() -> new SAMLException("Assertion :: AuthnStatements is not present!"));
    final Optional<String> optionalAuthnContextClassRef = Optional.ofNullable(authnStatement.getAuthnContext()).flatMap(authnContext -> Optional.ofNullable(authnContext.getAuthnContextClassRef())).flatMap(authnContextClassRef -> Optional.ofNullable(authnContextClassRef.getAuthnContextClassRef()));
    if (!optionalAuthnContextClassRef.filter(s -> idpConfiguration.getSpidProperties().getAuthnContextClassRef().contains(s)).isPresent()) {
        throw new SAMLException("Assertion :: AuthnContextClassRef is not correct!");
    }
    final SubjectConfirmation subjectConfirmation = assertion.getSubject().getSubjectConfirmations().stream().findFirst().orElseThrow(() -> new SAMLException("Assertion :: SubjectConfirmation not specified!"));
    Optional.ofNullable(subjectConfirmation.getMethod()).filter(s -> s.equalsIgnoreCase(SubjectConfirmation.METHOD_BEARER)).orElseThrow(() -> new SAMLException("Assertion :: SubjectConfirmation Method is not correct!"));
    final SubjectConfirmationData subjectConfirmationData = Optional.ofNullable(subjectConfirmation).flatMap(subjectConfirmation1 -> Optional.ofNullable(subjectConfirmation1.getSubjectConfirmationData())).orElseThrow(() -> new SAMLException("Assertion :: SubjectConfirmationData not specified!"));
    Optional.ofNullable(subjectConfirmationData.getRecipient()).filter(s -> s.equalsIgnoreCase(idpConfiguration.getSpidProperties().getDestination())).orElseThrow(() -> new SAMLException("Assertion :: SubjectConfirmationData -> Recipient is not correct!"));
    Optional.ofNullable(subjectConfirmationData.getInResponseTo()).filter(s -> s.equalsIgnoreCase(spidRequest.getId())).orElseThrow(() -> new SAMLException("Assertion :: SubjectConfirmationData -> InResponseTo is not correct!"));
    Optional.ofNullable(subjectConfirmationData.getNotOnOrAfter()).filter(dateTime -> dateTime.isAfter(spidRequest.getIssueIstant())).orElseThrow(() -> new SAMLException("Assertion :: SubjectConfirmationData -> NotOnOrAfter is not correct!"));
    Optional.ofNullable(assertion.getIssuer()).filter(issuer -> issuer.getValue().equalsIgnoreCase(spidRequest.getIssuer())).orElseThrow(() -> new SAMLException("Assertion :: Issuer is not correct!"));
    if (idpConfiguration.getSpidProperties().getValidateIssuerFormat()) {
        Optional.ofNullable(assertion.getIssuer().getFormat()).filter(format -> format.equalsIgnoreCase(NameIDType.ENTITY)).orElseThrow(() -> new SAMLException("Assertion :: Issuer -> Format is not correct!"));
    }
    enforceConditions(assertion.getConditions(), spidRequest);
}
Also used : XSString(org.opensaml.xml.schema.XSString) org.opensaml.saml2.core.impl(org.opensaml.saml2.core.impl) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) SPIDRequest(it.cnr.si.cool.jconon.spid.model.SPIDRequest) org.opensaml.xml.signature(org.opensaml.xml.signature) DefaultBootstrap(org.opensaml.DefaultBootstrap) IdpConfiguration(it.cnr.si.cool.jconon.spid.config.IdpConfiguration) BasicSecurityConfiguration(org.opensaml.xml.security.BasicSecurityConfiguration) HttpStatus(org.apache.commons.httpclient.HttpStatus) ValidationException(org.opensaml.xml.validation.ValidationException) Resource(org.springframework.core.io.Resource) CmisBindingsHelper(org.apache.chemistry.opencmis.client.bindings.impl.CmisBindingsHelper) MarshallingException(org.opensaml.xml.io.MarshallingException) java.security(java.security) ResourceBackedMetadataProvider(org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider) SignatureException(java.security.SignatureException) ResourceException(org.opensaml.util.resource.ResourceException) Deflater(java.util.zip.Deflater) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ZoneId(java.time.ZoneId) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) Signature(org.opensaml.xml.signature.Signature) X509Credential(org.opensaml.xml.security.x509.X509Credential) DateTimeParseException(java.time.format.DateTimeParseException) Stream(java.util.stream.Stream) SecurityException(org.opensaml.xml.security.SecurityException) SPIDRepository(it.cnr.si.cool.jconon.spid.repository.SPIDRepository) Environment(org.springframework.core.env.Environment) SAXException(org.xml.sax.SAXException) LocalDate(java.time.LocalDate) AbstractReloadingMetadataProvider(org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) SecurityHelper(org.opensaml.xml.security.SecurityHelper) CMISService(it.cnr.cool.cmis.service.CMISService) java.util(java.util) KeyDescriptor(org.opensaml.saml2.metadata.KeyDescriptor) BasicX509Credential(org.opensaml.xml.security.x509.BasicX509Credential) Scheduled(org.springframework.scheduling.annotation.Scheduled) DeflaterOutputStream(java.util.zip.DeflaterOutputStream) InitializingBean(org.springframework.beans.factory.InitializingBean) Base64(org.opensaml.xml.util.Base64) Credential(org.opensaml.xml.security.credential.Credential) Inject(javax.inject.Inject) Service(org.springframework.stereotype.Service) PageService(it.cnr.cool.service.PageService) UrlBuilder(org.apache.chemistry.opencmis.commons.impl.UrlBuilder) XMLObjectBuilderFactory(org.opensaml.xml.XMLObjectBuilderFactory) SAMLException(org.opensaml.common.SAMLException) InputSource(org.xml.sax.InputSource) org.opensaml.saml2.core(org.opensaml.saml2.core) Logger(org.slf4j.Logger) EntityDescriptor(org.opensaml.saml2.metadata.EntityDescriptor) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DateTime(org.joda.time.DateTime) AuthenticationException(it.cnr.si.cool.jconon.spid.config.AuthenticationException) CertificateException(java.security.cert.CertificateException) PageModel(it.cnr.cool.service.PageModel) SAMLVersion(org.opensaml.common.SAMLVersion) ApplicationContext(org.springframework.context.ApplicationContext) IdpEntry(it.cnr.si.cool.jconon.spid.model.IdpEntry) XSAny(org.opensaml.xml.schema.XSAny) Normalizer(java.text.Normalizer) KeyInfoHelper(org.opensaml.xml.security.keyinfo.KeyInfoHelper) DOMParser(com.sun.org.apache.xerces.internal.parsers.DOMParser) Element(org.w3c.dom.Element) Marshaller(org.opensaml.xml.io.Marshaller) java.io(java.io) UnmarshallingException(org.opensaml.xml.io.UnmarshallingException) BasicParserPool(org.opensaml.xml.parse.BasicParserPool) IDPSSODescriptor(org.opensaml.saml2.metadata.IDPSSODescriptor) DateTimeFormatter(java.time.format.DateTimeFormatter) Configuration(org.opensaml.xml.Configuration) ResponseSchemaValidator(org.opensaml.saml2.core.validator.ResponseSchemaValidator) MetadataProviderException(org.opensaml.saml2.metadata.provider.MetadataProviderException) UserService(it.cnr.cool.security.service.UserService) XMLHelper(org.opensaml.xml.util.XMLHelper) I18nService(it.cnr.cool.service.I18nService) ConfigurationException(org.opensaml.xml.ConfigurationException) SAMLVersion(org.opensaml.common.SAMLVersion) XSString(org.opensaml.xml.schema.XSString) SAMLException(org.opensaml.common.SAMLException) DateTime(org.joda.time.DateTime)

Example 12 with SAMLException

use of org.opensaml.common.SAMLException in project cool-jconon by consiglionazionaledellericerche.

the class SPIDIntegrationService method idpResponse.

public String idpResponse(String samlResponse) throws SAMLException, AuthenticationException {
    Response response = decodeAndValidateSamlResponse(samlResponse);
    final Map<String, String> collect = response.getAssertions().stream().map(Assertion::getAttributeStatements).flatMap(List<AttributeStatement>::stream).map(AttributeStatement::getAttributes).flatMap(List<Attribute>::stream).collect(HashMap::new, (m, attribute) -> m.put(attribute.getName(), getValue(attribute)), HashMap::putAll);
    CMISUser cmisUser = new CMISUser();
    cmisUser.setApplication(SPID);
    cmisUser.setFirstName(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getName(), null));
    cmisUser.setLastName(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getFamilyName(), null));
    cmisUser.setDataDiNascita(Optional.ofNullable(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getDateOfBirth(), null)).filter(s -> !s.isEmpty()).map(date -> {
        try {
            return Date.from(LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
        } catch (DateTimeParseException _ex) {
            LOGGER.warn("Cannot format date of birth", _ex);
            return null;
        }
    }).orElse(null));
    cmisUser.setCodicefiscale(Optional.ofNullable(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getFiscalNumber(), null)).map(cf -> cf.replaceAll("TINIT-", "")).orElse(null));
    cmisUser.setSesso(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getGender(), Optional.ofNullable(cmisUser.getCodicefiscale()).map(s -> Integer.valueOf(s.substring(9, 11)) > 40 ? "F" : "M").orElse(null)));
    cmisUser.setEmail(collect.getOrDefault(idpConfiguration.getSpidProperties().getAttribute().getEmail(), " "));
    String userName = normalize(Optional.ofNullable(cmisUser.getFirstName()).map(String::trim).filter(s -> !s.isEmpty()).orElseThrow(() -> new SAMLException("First Name cannot be empty"))).toLowerCase().concat("-").concat(normalize(Optional.ofNullable(cmisUser.getLastName()).map(String::trim).filter(s -> !s.isEmpty()).orElseThrow(() -> new SAMLException("Last Name cannot be empty"))).toLowerCase());
    Optional<CMISUser> userByCodiceFiscale = Optional.ofNullable(userService.findUserByCodiceFiscale(cmisUser.getCodicefiscale(), cmisService.getAdminSession(), userName));
    if (userByCodiceFiscale.isPresent()) {
        if (!Optional.ofNullable(userByCodiceFiscale.get().getEmail()).equals(Optional.ofNullable(cmisUser.getEmail())) && Optional.ofNullable(userByCodiceFiscale.get().getApplication()).filter(s -> s.equalsIgnoreCase(SPID)).isPresent()) {
            cmisUser.setUserName(userByCodiceFiscale.get().getUserName());
            userByCodiceFiscale = Optional.ofNullable(userService.updateUser(cmisUser));
        }
        return createTicketForUser(userByCodiceFiscale.get());
    } else {
        // Verifico se l'utenza ha lo stesso codice fiscale
        try {
            Optional<CMISUser> cmisUser2 = Optional.ofNullable(userService.loadUserForConfirm(userName)).filter(cmisUser1 -> cmisUser1.getCodicefiscale().equalsIgnoreCase(cmisUser.getCodicefiscale()));
            if (cmisUser2.isPresent()) {
                if (!Optional.ofNullable(cmisUser2.get().getEmail()).equals(Optional.ofNullable(cmisUser.getEmail())) && Optional.ofNullable(cmisUser2.get().getApplication()).filter(s -> s.equalsIgnoreCase(SPID)).isPresent()) {
                    cmisUser.setUserName(cmisUser2.get().getUserName());
                    cmisUser2 = Optional.ofNullable(userService.updateUser(cmisUser));
                }
                return createTicketForUser(cmisUser2.get());
            }
        } catch (CoolUserFactoryException _ex) {
            LOGGER.trace("SPID Username {} not found", userName);
        }
        if (!userService.isUserExists(userName)) {
            cmisUser.setUserName(userName);
        } else {
            for (int i = 1; i < 20; i++) {
                final String concatUsername = userName.concat("0").concat(String.valueOf(i));
                if (!userService.isUserExists(concatUsername)) {
                    cmisUser.setUserName(concatUsername);
                    break;
                }
            }
        }
        final CMISUser user = userService.createUser(cmisUser);
        userService.enableAccount(user.getUserName());
        return createTicketForUser(user);
    }
}
Also used : XSString(org.opensaml.xml.schema.XSString) org.opensaml.saml2.core.impl(org.opensaml.saml2.core.impl) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) SPIDRequest(it.cnr.si.cool.jconon.spid.model.SPIDRequest) org.opensaml.xml.signature(org.opensaml.xml.signature) DefaultBootstrap(org.opensaml.DefaultBootstrap) IdpConfiguration(it.cnr.si.cool.jconon.spid.config.IdpConfiguration) BasicSecurityConfiguration(org.opensaml.xml.security.BasicSecurityConfiguration) HttpStatus(org.apache.commons.httpclient.HttpStatus) ValidationException(org.opensaml.xml.validation.ValidationException) Resource(org.springframework.core.io.Resource) CmisBindingsHelper(org.apache.chemistry.opencmis.client.bindings.impl.CmisBindingsHelper) MarshallingException(org.opensaml.xml.io.MarshallingException) java.security(java.security) ResourceBackedMetadataProvider(org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider) SignatureException(java.security.SignatureException) ResourceException(org.opensaml.util.resource.ResourceException) Deflater(java.util.zip.Deflater) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ZoneId(java.time.ZoneId) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) Signature(org.opensaml.xml.signature.Signature) X509Credential(org.opensaml.xml.security.x509.X509Credential) DateTimeParseException(java.time.format.DateTimeParseException) Stream(java.util.stream.Stream) SecurityException(org.opensaml.xml.security.SecurityException) SPIDRepository(it.cnr.si.cool.jconon.spid.repository.SPIDRepository) Environment(org.springframework.core.env.Environment) SAXException(org.xml.sax.SAXException) LocalDate(java.time.LocalDate) AbstractReloadingMetadataProvider(org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException) SecurityHelper(org.opensaml.xml.security.SecurityHelper) CMISService(it.cnr.cool.cmis.service.CMISService) java.util(java.util) KeyDescriptor(org.opensaml.saml2.metadata.KeyDescriptor) BasicX509Credential(org.opensaml.xml.security.x509.BasicX509Credential) Scheduled(org.springframework.scheduling.annotation.Scheduled) DeflaterOutputStream(java.util.zip.DeflaterOutputStream) InitializingBean(org.springframework.beans.factory.InitializingBean) Base64(org.opensaml.xml.util.Base64) Credential(org.opensaml.xml.security.credential.Credential) Inject(javax.inject.Inject) Service(org.springframework.stereotype.Service) PageService(it.cnr.cool.service.PageService) UrlBuilder(org.apache.chemistry.opencmis.commons.impl.UrlBuilder) XMLObjectBuilderFactory(org.opensaml.xml.XMLObjectBuilderFactory) SAMLException(org.opensaml.common.SAMLException) InputSource(org.xml.sax.InputSource) org.opensaml.saml2.core(org.opensaml.saml2.core) Logger(org.slf4j.Logger) EntityDescriptor(org.opensaml.saml2.metadata.EntityDescriptor) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DateTime(org.joda.time.DateTime) AuthenticationException(it.cnr.si.cool.jconon.spid.config.AuthenticationException) CertificateException(java.security.cert.CertificateException) PageModel(it.cnr.cool.service.PageModel) SAMLVersion(org.opensaml.common.SAMLVersion) ApplicationContext(org.springframework.context.ApplicationContext) IdpEntry(it.cnr.si.cool.jconon.spid.model.IdpEntry) XSAny(org.opensaml.xml.schema.XSAny) Normalizer(java.text.Normalizer) KeyInfoHelper(org.opensaml.xml.security.keyinfo.KeyInfoHelper) DOMParser(com.sun.org.apache.xerces.internal.parsers.DOMParser) Element(org.w3c.dom.Element) Marshaller(org.opensaml.xml.io.Marshaller) java.io(java.io) UnmarshallingException(org.opensaml.xml.io.UnmarshallingException) BasicParserPool(org.opensaml.xml.parse.BasicParserPool) IDPSSODescriptor(org.opensaml.saml2.metadata.IDPSSODescriptor) DateTimeFormatter(java.time.format.DateTimeFormatter) Configuration(org.opensaml.xml.Configuration) ResponseSchemaValidator(org.opensaml.saml2.core.validator.ResponseSchemaValidator) MetadataProviderException(org.opensaml.saml2.metadata.provider.MetadataProviderException) UserService(it.cnr.cool.security.service.UserService) XMLHelper(org.opensaml.xml.util.XMLHelper) I18nService(it.cnr.cool.service.I18nService) ConfigurationException(org.opensaml.xml.ConfigurationException) CMISUser(it.cnr.cool.security.service.impl.alfresco.CMISUser) XSString(org.opensaml.xml.schema.XSString) SAMLException(org.opensaml.common.SAMLException) DateTimeParseException(java.time.format.DateTimeParseException) CoolUserFactoryException(it.cnr.cool.exception.CoolUserFactoryException)

Example 13 with SAMLException

use of org.opensaml.common.SAMLException in project cloud-pipeline by epam.

the class OptionalSAMLLogoutFilter method processLogout.

/**
 * In case request parameter of name "local" is set to true or there is no authenticated user
 * only local logout will be performed and user will be redirected to the success page.
 * Otherwise global logout procedure is initialized.
 *
 * @param request  http request
 * @param response http response
 * @param chain    chain
 * @throws IOException      error
 * @throws ServletException error
 */
public void processLogout(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (requiresLogout(request, response)) {
        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null && isGlobalLogout(request, auth)) {
                Assert.isInstanceOf(SAMLCredential.class, auth.getCredentials(), "Authentication object doesn't contain SAML credential, cannot perform global logout");
                // Terminate the session first
                for (LogoutHandler handler : globalHandlers) {
                    handler.logout(request, response, auth);
                }
                // Notify session participants using SAML Single Logout profile
                SAMLCredential credential = (SAMLCredential) auth.getCredentials();
                request.setAttribute(SAMLConstants.LOCAL_ENTITY_ID, credential.getLocalEntityID());
                request.setAttribute(SAMLConstants.PEER_ENTITY_ID, credential.getRemoteEntityID());
                SAMLMessageContext context = contextProvider.getLocalAndPeerEntity(request, response);
                try {
                    profile.sendLogoutRequest(context, credential);
                    samlLogger.log(SAMLConstants.LOGOUT_REQUEST, SAMLConstants.SUCCESS, context);
                } catch (MetadataProviderException e) {
                    logger.debug(e.getMessage(), e);
                    super.doFilter(request, response, chain);
                }
            } else {
                super.doFilter(request, response, chain);
            }
        } catch (SAMLException e) {
            logger.debug("Error initializing global logout", e);
            throw new ServletException("Error initializing global logout", e);
        } catch (MetadataProviderException e) {
            logger.debug("Error processing metadata", e);
            throw new ServletException("Error processing metadata", e);
        } catch (MessageEncodingException e) {
            logger.debug("Error encoding outgoing message", e);
            throw new ServletException("Error encoding outgoing message", e);
        }
    } else {
        chain.doFilter(request, response);
    }
}
Also used : ServletException(javax.servlet.ServletException) SAMLMessageContext(org.springframework.security.saml.context.SAMLMessageContext) SAMLCredential(org.springframework.security.saml.SAMLCredential) Authentication(org.springframework.security.core.Authentication) LogoutHandler(org.springframework.security.web.authentication.logout.LogoutHandler) MessageEncodingException(org.opensaml.ws.message.encoder.MessageEncodingException) MetadataProviderException(org.opensaml.saml2.metadata.provider.MetadataProviderException) SAMLException(org.opensaml.common.SAMLException)

Example 14 with SAMLException

use of org.opensaml.common.SAMLException in project cloud-pipeline by epam.

the class SAMLProxyAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SAMLProxyAuthentication auth = (SAMLProxyAuthentication) authentication;
    List<ExternalServiceEndpoint> externalServices = preferenceManager.getPreference(SYSTEM_EXTERNAL_SERVICES_ENDPOINTS);
    if (CollectionUtils.isEmpty(externalServices)) {
        throw new AuthenticationServiceException(messageHelper.getMessage(MessageConstants.ERROR_PROXY_SECURITY_CONFIG_MISSING));
    }
    if (StringUtils.isNotBlank(auth.getRawSamlResponse())) {
        try {
            Response decoded = CustomSamlClient.decodeSamlResponse(auth.getRawSamlResponse());
            String endpointId = // cut out SSO endpoint
            decoded.getDestination().substring(0, decoded.getDestination().length() - CustomSamlClient.SSO_ENDPOINT.length());
            Optional<ExternalServiceEndpoint> endpointOpt = externalServices.stream().filter(e -> e.getEndpointId().equals(endpointId)).findFirst();
            if (endpointOpt.isPresent()) {
                return validateAuthentication(auth, decoded, endpointId, endpointOpt.get());
            } else {
                throw new AuthenticationServiceException("Authentication error: unexpected external service");
            }
        } catch (SAMLException e) {
            throw new AuthenticationServiceException("Authentication error: ", e);
        }
    } else {
        throw new AuthenticationServiceException("Authentication error: missing SAML token");
    }
}
Also used : Response(org.opensaml.saml2.core.Response) PreferenceManager(com.epam.pipeline.manager.preference.PreferenceManager) MessageConstants(com.epam.pipeline.common.MessageConstants) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) SYSTEM_EXTERNAL_SERVICES_ENDPOINTS(com.epam.pipeline.manager.preference.SystemPreferences.SYSTEM_EXTERNAL_SERVICES_ENDPOINTS) Autowired(org.springframework.beans.factory.annotation.Autowired) AuthenticationProvider(org.springframework.security.authentication.AuthenticationProvider) IOException(java.io.IOException) ExternalServiceEndpoint(com.epam.pipeline.security.ExternalServiceEndpoint) StringUtils(org.apache.commons.lang3.StringUtils) File(java.io.File) CollectionUtils(org.apache.commons.collections4.CollectionUtils) List(java.util.List) MessageHelper(com.epam.pipeline.common.MessageHelper) Response(org.opensaml.saml2.core.Response) Optional(java.util.Optional) AuthenticationException(org.springframework.security.core.AuthenticationException) FileReader(java.io.FileReader) Authentication(org.springframework.security.core.Authentication) SAMLException(org.opensaml.common.SAMLException) SAMLException(org.opensaml.common.SAMLException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ExternalServiceEndpoint(com.epam.pipeline.security.ExternalServiceEndpoint)

Example 15 with SAMLException

use of org.opensaml.common.SAMLException in project cloud-pipeline by epam.

the class CustomSamlClient method validateSignature.

private void validateSignature(Response response) throws SAMLException {
    Signature responseSignature = response.getSignature();
    Signature assertionSignature = response.getAssertions().get(0).getSignature();
    if (responseSignature == null && assertionSignature == null) {
        throw new SAMLException("No signature is present in either response or assertion");
    }
    if (responseSignature != null && !validate(responseSignature)) {
        throw new SAMLException("The response signature is invalid");
    }
    if (assertionSignature != null && !validate(assertionSignature)) {
        throw new SAMLException("The assertion signature is invalid");
    }
}
Also used : Signature(org.opensaml.xml.signature.Signature) SAMLException(org.opensaml.common.SAMLException)

Aggregations

SAMLException (org.opensaml.common.SAMLException)17 MetadataProviderException (org.opensaml.saml2.metadata.provider.MetadataProviderException)9 Logger (org.slf4j.Logger)8 LoggerFactory (org.slf4j.LoggerFactory)8 Autowired (org.springframework.beans.factory.annotation.Autowired)8 DOMParser (com.sun.org.apache.xerces.internal.parsers.DOMParser)7 AuthenticationException (it.cnr.si.cool.jconon.spid.config.AuthenticationException)6 IdpConfiguration (it.cnr.si.cool.jconon.spid.config.IdpConfiguration)6 IdpEntry (it.cnr.si.cool.jconon.spid.model.IdpEntry)6 StandardCharsets (java.nio.charset.StandardCharsets)6 Collectors (java.util.stream.Collectors)6 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 CMISService (it.cnr.cool.cmis.service.CMISService)5 CoolUserFactoryException (it.cnr.cool.exception.CoolUserFactoryException)5 UserService (it.cnr.cool.security.service.UserService)5 CMISUser (it.cnr.cool.security.service.impl.alfresco.CMISUser)5 I18nService (it.cnr.cool.service.I18nService)5 PageModel (it.cnr.cool.service.PageModel)5 PageService (it.cnr.cool.service.PageService)5 SPIDRequest (it.cnr.si.cool.jconon.spid.model.SPIDRequest)5