Search in sources :

Example 6 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 7 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 8 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)

Example 9 with SAMLException

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

the class SAMLProxyFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (!urlMatches(request)) {
        filterChain.doFilter(request, response);
        return;
    }
    List<ExternalServiceEndpoint> externalServices = preferenceManager.getPreference(SYSTEM_EXTERNAL_SERVICES_ENDPOINTS);
    if (CollectionUtils.isEmpty(externalServices)) {
        LOGGER.warn(messageHelper.getMessage(MessageConstants.ERROR_PROXY_SECURITY_CONFIG_MISSING));
    } else {
        String samlResponse = request.getParameter("SAMLResponse");
        if (StringUtils.isNotBlank(samlResponse)) {
            try {
                Response decoded = CustomSamlClient.decodeSamlResponse(samlResponse);
                String audience = ListUtils.emptyIfNull(decoded.getAssertions()).stream().findFirst().map(Assertion::getConditions).map(conditions -> ListUtils.emptyIfNull(conditions.getAudienceRestrictions()).stream().findFirst()).flatMap(Function.identity()).map(audienceRestriction -> ListUtils.emptyIfNull(audienceRestriction.getAudiences()).stream().findFirst()).flatMap(Function.identity()).map(Audience::getAudienceURI).orElse(StringUtils.EMPTY);
                LOGGER.debug("Received SAMLResponse for audience: {}", audience);
                Optional<ExternalServiceEndpoint> endpointOpt = externalServices.stream().filter(e -> !StringUtils.EMPTY.equals(audience) && e.getEndpointId().equals(audience)).findFirst();
                if (endpointOpt.isPresent()) {
                    authenticate(samlResponse, decoded, audience, endpointOpt.get());
                }
            } catch (SAMLException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }
    filterChain.doFilter(request, response);
}
Also used : Response(org.opensaml.saml2.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) SamlResponse(com.coveo.saml.SamlResponse) FilterChain(javax.servlet.FilterChain) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) ServletException(javax.servlet.ServletException) MessageConstants(com.epam.pipeline.common.MessageConstants) LoggerFactory(org.slf4j.LoggerFactory) SYSTEM_EXTERNAL_SERVICES_ENDPOINTS(com.epam.pipeline.manager.preference.SystemPreferences.SYSTEM_EXTERNAL_SERVICES_ENDPOINTS) Autowired(org.springframework.beans.factory.annotation.Autowired) OncePerRequestFilter(org.springframework.web.filter.OncePerRequestFilter) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) CollectionUtils(org.apache.commons.collections4.CollectionUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserContext(com.epam.pipeline.security.UserContext) MessageHelper(com.epam.pipeline.common.MessageHelper) Response(org.opensaml.saml2.core.Response) ListUtils(org.apache.commons.collections4.ListUtils) AntPathMatcher(org.springframework.util.AntPathMatcher) Assertion(org.opensaml.saml2.core.Assertion) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) PipelineUser(com.epam.pipeline.entity.user.PipelineUser) SAMLException(org.opensaml.common.SAMLException) Audience(org.opensaml.saml2.core.Audience) PreferenceManager(com.epam.pipeline.manager.preference.PreferenceManager) Logger(org.slf4j.Logger) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ExternalServiceEndpoint(com.epam.pipeline.security.ExternalServiceEndpoint) File(java.io.File) SamlResponse(com.coveo.saml.SamlResponse) List(java.util.List) UserManager(com.epam.pipeline.manager.user.UserManager) Optional(java.util.Optional) FileReader(java.io.FileReader) Assertion(org.opensaml.saml2.core.Assertion) SAMLException(org.opensaml.common.SAMLException) ExternalServiceEndpoint(com.epam.pipeline.security.ExternalServiceEndpoint)

Example 10 with SAMLException

use of org.opensaml.common.SAMLException in project Insights by CognizantOneDevOps.

the class InsightsSAMLAuthenticationProviderImpl method authenticate.

/**
 * Used to authenticate initial SAML login request, It will redirect user to
 * service provider login URL and then fetch necessary user detail.
 * It also create ExpiringUsernameAuthenticationToken and set it in spring
 * security context
 */
@Override
public Authentication authenticate(Authentication authentication) {
    log.debug(" Inside InsightsSAMLAuthenticationProviderImpl === ");
    if (!supports(authentication.getClass())) {
        throw new IllegalArgumentException("Only SAMLAuthenticationToken is supported, " + authentication.getClass() + " was attempted");
    }
    SAMLAuthenticationToken token = (SAMLAuthenticationToken) authentication;
    SAMLMessageContext context = token.getCredentials();
    if (context == null) {
        throw new AuthenticationServiceException("SAML message context is not available in the authentication token");
    }
    SAMLCredential credential;
    try {
        if (SAMLConstants.SAML2_WEBSSO_PROFILE_URI.equals(context.getCommunicationProfileId())) {
            credential = consumer.processAuthenticationResponse(context);
        } else if (SAMLConstants.SAML2_HOK_WEBSSO_PROFILE_URI.equals(context.getCommunicationProfileId())) {
            credential = hokConsumer.processAuthenticationResponse(context);
        } else {
            throw new SAMLException("Unsupported profile encountered in the context " + context.getCommunicationProfileId());
        }
    } catch (SAMLRuntimeException e) {
        log.debug("Error validating SAML message ", e);
        samlLogger.log(SAMLConstants.AUTH_N_RESPONSE, SAMLConstants.FAILURE, context, e);
        throw new AuthenticationServiceException("Error validating SAML message.", e);
    } catch (SAMLException e) {
        log.debug("Error validating SAML message ", e);
        samlLogger.log(SAMLConstants.AUTH_N_RESPONSE, SAMLConstants.FAILURE, context, e);
        throw new AuthenticationServiceException("Error validating SAML message..", e);
    } catch (ValidationException e) {
        log.debug("Error validating signature ", e);
        samlLogger.log(SAMLConstants.AUTH_N_RESPONSE, SAMLConstants.FAILURE, context, e);
        throw new AuthenticationServiceException("Error validating SAML message signature", e);
    } catch (org.opensaml.xml.security.SecurityException e) {
        log.debug("Error validating signature", e);
        samlLogger.log(SAMLConstants.AUTH_N_RESPONSE, SAMLConstants.FAILURE, context, e);
        throw new AuthenticationServiceException("Error validating SAML message signature", e);
    } catch (DecryptionException e) {
        log.debug("Error decrypting SAML message", e);
        samlLogger.log(SAMLConstants.AUTH_N_RESPONSE, SAMLConstants.FAILURE, context, e);
        throw new AuthenticationServiceException("Error decrypting SAML message", e);
    }
    SamlUserDetails userDetails = (SamlUserDetails) getUserDetails(credential);
    Object principal = getPrincipal(credential, userDetails);
    List<GrantedAuthority> updatedAuthorities = new ArrayList<>();
    updatedAuthorities.add(SpringAuthority.valueOf("Viewer"));
    Date expiration = getExpirationDate(credential);
    SAMLCredential authenticationCredential = excludeCredential ? null : credential;
    ExpiringUsernameAuthenticationToken result = new ExpiringUsernameAuthenticationToken(expiration, principal, authenticationCredential, updatedAuthorities);
    result.setDetails(userDetails);
    samlLogger.log(SAMLConstants.AUTH_N_RESPONSE, SAMLConstants.SUCCESS, context, result, null);
    return result;
}
Also used : ValidationException(org.opensaml.xml.validation.ValidationException) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ExpiringUsernameAuthenticationToken(org.springframework.security.providers.ExpiringUsernameAuthenticationToken) ArrayList(java.util.ArrayList) SAMLRuntimeException(org.opensaml.common.SAMLRuntimeException) SAMLAuthenticationToken(org.springframework.security.saml.SAMLAuthenticationToken) SAMLException(org.opensaml.common.SAMLException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) Date(java.util.Date) SAMLMessageContext(org.springframework.security.saml.context.SAMLMessageContext) SAMLCredential(org.springframework.security.saml.SAMLCredential) DecryptionException(org.opensaml.xml.encryption.DecryptionException)

Aggregations

SAMLException (org.opensaml.common.SAMLException)11 SAMLMessageContext (org.springframework.security.saml.context.SAMLMessageContext)5 IOException (java.io.IOException)4 List (java.util.List)3 Optional (java.util.Optional)3 ServletException (javax.servlet.ServletException)3 Response (org.opensaml.saml2.core.Response)3 MetadataProviderException (org.opensaml.saml2.metadata.provider.MetadataProviderException)3 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)3 SamlResponse (com.coveo.saml.SamlResponse)2 MessageConstants (com.epam.pipeline.common.MessageConstants)2 MessageHelper (com.epam.pipeline.common.MessageHelper)2 PreferenceManager (com.epam.pipeline.manager.preference.PreferenceManager)2 SYSTEM_EXTERNAL_SERVICES_ENDPOINTS (com.epam.pipeline.manager.preference.SystemPreferences.SYSTEM_EXTERNAL_SERVICES_ENDPOINTS)2 ExternalServiceEndpoint (com.epam.pipeline.security.ExternalServiceEndpoint)2 DOMParser (com.sun.org.apache.xerces.internal.parsers.DOMParser)2 File (java.io.File)2 FileReader (java.io.FileReader)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2