Search in sources :

Example 1 with org.opensaml.saml.saml2.metadata

use of org.opensaml.saml.saml2.metadata in project cas by apereo.

the class BaseSamlRegisteredServiceAttributeReleasePolicy method getAttributesInternal.

@Override
protected Map<String, Object> getAttributesInternal(final Map<String, Object> attrs, final RegisteredService service) {
    if (service instanceof SamlRegisteredService) {
        final SamlRegisteredService saml = (SamlRegisteredService) service;
        final HttpServletRequest request = WebUtils.getHttpServletRequestFromRequestAttributes();
        if (request == null) {
            LOGGER.warn("Could not locate the request context to process attributes");
            return super.getAttributesInternal(attrs, service);
        }
        String entityId = request.getParameter(SamlProtocolConstants.PARAMETER_ENTITY_ID);
        if (StringUtils.isBlank(entityId)) {
            final String svcParam = request.getParameter(CasProtocolConstants.PARAMETER_SERVICE);
            if (StringUtils.isNotBlank(svcParam)) {
                try {
                    final URIBuilder builder = new URIBuilder(svcParam);
                    entityId = builder.getQueryParams().stream().filter(p -> p.getName().equals(SamlProtocolConstants.PARAMETER_ENTITY_ID)).map(NameValuePair::getValue).findFirst().orElse(StringUtils.EMPTY);
                } catch (final Exception e) {
                    LOGGER.error(e.getMessage());
                }
            }
        }
        final ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
        if (ctx == null) {
            LOGGER.warn("Could not locate the application context to process attributes");
            return super.getAttributesInternal(attrs, service);
        }
        final SamlRegisteredServiceCachingMetadataResolver resolver = ctx.getBean("defaultSamlRegisteredServiceCachingMetadataResolver", SamlRegisteredServiceCachingMetadataResolver.class);
        final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> facade = SamlRegisteredServiceServiceProviderMetadataFacade.get(resolver, saml, entityId);
        if (facade == null || !facade.isPresent()) {
            LOGGER.warn("Could not locate metadata for [{}] to process attributes", entityId);
            return super.getAttributesInternal(attrs, service);
        }
        final EntityDescriptor input = facade.get().getEntityDescriptor();
        if (input == null) {
            LOGGER.warn("Could not locate entity descriptor for [{}] to process attributes", entityId);
            return super.getAttributesInternal(attrs, service);
        }
        return getAttributesForSamlRegisteredService(attrs, saml, ctx, resolver, facade.get(), input);
    }
    return super.getAttributesInternal(attrs, service);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) ApplicationContext(org.springframework.context.ApplicationContext) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 2 with org.opensaml.saml.saml2.metadata

use of org.opensaml.saml.saml2.metadata in project cas by apereo.

the class WsFederationHelper method parseTokenFromString.

/**
     * parseTokenFromString converts a raw wresult and extracts it into an assertion.
     *
     * @param wresult the raw token returned by the IdP
     * @param config  the config
     * @return an assertion
     */
public Assertion parseTokenFromString(final String wresult, final WsFederationConfiguration config) {
    LOGGER.debug("Result token received from ADFS is [{}]", wresult);
    try (InputStream in = new ByteArrayInputStream(wresult.getBytes(StandardCharsets.UTF_8))) {
        LOGGER.debug("Parsing token into a document");
        final Document document = configBean.getParserPool().parse(in);
        final Element metadataRoot = document.getDocumentElement();
        final UnmarshallerFactory unmarshallerFactory = configBean.getUnmarshallerFactory();
        final Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot);
        if (unmarshaller == null) {
            throw new IllegalArgumentException("Unmarshaller for the metadata root element cannot be determined");
        }
        LOGGER.debug("Unmarshalling the document into a security token response");
        final RequestSecurityTokenResponse rsToken = (RequestSecurityTokenResponse) unmarshaller.unmarshall(metadataRoot);
        if (rsToken == null || rsToken.getRequestedSecurityToken() == null) {
            throw new IllegalArgumentException("Request security token response is null");
        }
        //Get our SAML token
        LOGGER.debug("Locating list of requested security tokens");
        final List<RequestedSecurityToken> rst = rsToken.getRequestedSecurityToken();
        if (rst.isEmpty()) {
            throw new IllegalArgumentException("No requested security token response is provided in the response");
        }
        LOGGER.debug("Locating the first occurrence of a requested security token in the list");
        final RequestedSecurityToken reqToken = rst.get(0);
        if (reqToken.getSecurityTokens() == null || reqToken.getSecurityTokens().isEmpty()) {
            throw new IllegalArgumentException("Requested security token response is not carrying any security tokens");
        }
        Assertion assertion = null;
        LOGGER.debug("Locating the first occurrence of a security token from the requested security token");
        XMLObject securityToken = reqToken.getSecurityTokens().get(0);
        if (securityToken instanceof EncryptedData) {
            try {
                LOGGER.debug("Security token is encrypted. Attempting to decrypt to extract the assertion");
                final EncryptedData encryptedData = EncryptedData.class.cast(securityToken);
                final Decrypter decrypter = buildAssertionDecrypter(config);
                LOGGER.debug("Built an instance of [{}]", decrypter.getClass().getName());
                securityToken = decrypter.decryptData(encryptedData);
            } catch (final Exception e) {
                throw new IllegalArgumentException("Unable to decrypt security token", e);
            }
        }
        if (securityToken instanceof Assertion) {
            LOGGER.debug("Security token is an assertion.");
            assertion = Assertion.class.cast(securityToken);
        }
        if (assertion == null) {
            throw new IllegalArgumentException("Could not extract or decrypt an assertion based on the security token provided");
        }
        LOGGER.debug("Extracted assertion successfully: [{}]", assertion);
        return assertion;
    } catch (final Exception ex) {
        LOGGER.warn(ex.getMessage());
        return null;
    }
}
Also used : RequestedSecurityToken(org.opensaml.soap.wsfed.RequestedSecurityToken) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) Assertion(org.opensaml.saml.saml1.core.Assertion) XMLObject(org.opensaml.core.xml.XMLObject) Decrypter(org.opensaml.saml.saml2.encryption.Decrypter) UnmarshallerFactory(org.opensaml.core.xml.io.UnmarshallerFactory) Document(org.w3c.dom.Document) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) SecurityException(org.opensaml.security.SecurityException) ByteArrayInputStream(java.io.ByteArrayInputStream) EncryptedData(org.opensaml.xmlsec.encryption.EncryptedData) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) RequestSecurityTokenResponse(org.opensaml.soap.wsfed.RequestSecurityTokenResponse)

Example 3 with org.opensaml.saml.saml2.metadata

use of org.opensaml.saml.saml2.metadata in project cas by apereo.

the class GoogleAccountsServiceResponseBuilder method constructSamlResponse.

/**
     * Construct SAML response.
     * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
     *
     * @param service the service
     * @return the SAML response
     */
protected String constructSamlResponse(final GoogleAccountsService service) {
    final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
    final ZonedDateTime notBeforeIssueInstant = ZonedDateTime.parse("2003-04-17T00:46:02Z");
    final RegisteredService registeredService = servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE);
    }
    final String userId = registeredService.getUsernameAttributeProvider().resolveUsername(service.getPrincipal(), service);
    final org.opensaml.saml.saml2.core.Response response = this.samlObjectBuilder.newResponse(this.samlObjectBuilder.generateSecureRandomId(), currentDateTime, service.getId(), service);
    response.setStatus(this.samlObjectBuilder.newStatus(StatusCode.SUCCESS, null));
    final String sessionIndex = '_' + String.valueOf(Math.abs(new SecureRandom().nextLong()));
    final AuthnStatement authnStatement = this.samlObjectBuilder.newAuthnStatement(AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime, sessionIndex);
    final Assertion assertion = this.samlObjectBuilder.newAssertion(authnStatement, casServerPrefix, notBeforeIssueInstant, this.samlObjectBuilder.generateSecureRandomId());
    final Conditions conditions = this.samlObjectBuilder.newConditions(notBeforeIssueInstant, currentDateTime.plusSeconds(this.skewAllowance), service.getId());
    assertion.setConditions(conditions);
    final Subject subject = this.samlObjectBuilder.newSubject(NameID.EMAIL, userId, service.getId(), currentDateTime.plusSeconds(this.skewAllowance), service.getRequestId());
    assertion.setSubject(subject);
    response.getAssertions().add(assertion);
    final StringWriter writer = new StringWriter();
    this.samlObjectBuilder.marshalSamlXmlObject(response, writer);
    final String result = writer.toString();
    LOGGER.debug("Generated Google SAML response: [{}]", result);
    return result;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) Assertion(org.opensaml.saml.saml2.core.Assertion) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) SecureRandom(java.security.SecureRandom) Conditions(org.opensaml.saml.saml2.core.Conditions) Subject(org.opensaml.saml.saml2.core.Subject) StringWriter(java.io.StringWriter) ZonedDateTime(java.time.ZonedDateTime) AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement)

Example 4 with org.opensaml.saml.saml2.metadata

use of org.opensaml.saml.saml2.metadata in project cas by apereo.

the class MetadataUIUtils method locateMetadataUserInterfaceForEntityId.

/**
     * Locate mdui for entity id simple metadata ui info.
     *
     * @param entityDescriptor  the entity descriptor
     * @param entityId          the entity id
     * @param registeredService the registered service
     * @return the simple metadata ui info
     */
public static SamlMetadataUIInfo locateMetadataUserInterfaceForEntityId(final EntityDescriptor entityDescriptor, final String entityId, final RegisteredService registeredService) {
    final SamlMetadataUIInfo mdui = new SamlMetadataUIInfo(registeredService);
    if (entityDescriptor == null) {
        LOGGER.debug("Entity descriptor not found for [{}]", entityId);
        return mdui;
    }
    final SPSSODescriptor spssoDescriptor = getSPSsoDescriptor(entityDescriptor);
    if (spssoDescriptor == null) {
        LOGGER.debug("SP SSO descriptor not found for [{}]", entityId);
        return mdui;
    }
    final Extensions extensions = spssoDescriptor.getExtensions();
    if (extensions == null) {
        LOGGER.debug("No extensions in the SP SSO descriptor are found for [{}]", UIInfo.DEFAULT_ELEMENT_NAME.getNamespaceURI());
        return mdui;
    }
    final List<XMLObject> spExtensions = extensions.getUnknownXMLObjects(UIInfo.DEFAULT_ELEMENT_NAME);
    if (spExtensions.isEmpty()) {
        LOGGER.debug("No extensions in the SP SSO descriptor are located for [{}]", UIInfo.DEFAULT_ELEMENT_NAME.getNamespaceURI());
        return mdui;
    }
    spExtensions.stream().filter(UIInfo.class::isInstance).forEach(obj -> {
        final UIInfo uiInfo = (UIInfo) obj;
        LOGGER.debug("Found MDUI info for [{}]", entityId);
        mdui.setUIInfo(uiInfo);
    });
    return mdui;
}
Also used : SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) UIInfo(org.opensaml.saml.ext.saml2mdui.UIInfo) XMLObject(org.opensaml.core.xml.XMLObject) Extensions(org.opensaml.saml.saml2.metadata.Extensions)

Example 5 with org.opensaml.saml.saml2.metadata

use of org.opensaml.saml.saml2.metadata in project cas by apereo.

the class BaseSamlRegisteredServiceAttributeReleasePolicy method getAttributesInternal.

@Override
public Map<String, Object> getAttributesInternal(final Principal principal, final Map<String, Object> attributes, final RegisteredService service) {
    if (service instanceof SamlRegisteredService) {
        final SamlRegisteredService saml = (SamlRegisteredService) service;
        final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        if (request == null) {
            LOGGER.warn("Could not locate the request context to process attributes");
            return super.getAttributesInternal(principal, attributes, service);
        }
        String entityId = request.getParameter(SamlProtocolConstants.PARAMETER_ENTITY_ID);
        if (StringUtils.isBlank(entityId)) {
            final String svcParam = request.getParameter(CasProtocolConstants.PARAMETER_SERVICE);
            if (StringUtils.isNotBlank(svcParam)) {
                try {
                    final URIBuilder builder = new URIBuilder(svcParam);
                    entityId = builder.getQueryParams().stream().filter(p -> p.getName().equals(SamlProtocolConstants.PARAMETER_ENTITY_ID)).map(NameValuePair::getValue).findFirst().orElse(StringUtils.EMPTY);
                } catch (final Exception e) {
                    LOGGER.error(e.getMessage());
                }
            }
        }
        final ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
        if (ctx == null) {
            LOGGER.warn("Could not locate the application context to process attributes");
            return super.getAttributesInternal(principal, attributes, service);
        }
        final SamlRegisteredServiceCachingMetadataResolver resolver = ctx.getBean("defaultSamlRegisteredServiceCachingMetadataResolver", SamlRegisteredServiceCachingMetadataResolver.class);
        final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> facade = SamlRegisteredServiceServiceProviderMetadataFacade.get(resolver, saml, entityId);
        if (facade == null || !facade.isPresent()) {
            LOGGER.warn("Could not locate metadata for [{}] to process attributes", entityId);
            return super.getAttributesInternal(principal, attributes, service);
        }
        final EntityDescriptor input = facade.get().getEntityDescriptor();
        if (input == null) {
            LOGGER.warn("Could not locate entity descriptor for [{}] to process attributes", entityId);
            return super.getAttributesInternal(principal, attributes, service);
        }
        return getAttributesForSamlRegisteredService(attributes, saml, ctx, resolver, facade.get(), input);
    }
    return super.getAttributesInternal(principal, attributes, service);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) ApplicationContext(org.springframework.context.ApplicationContext) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) URIBuilder(org.apache.http.client.utils.URIBuilder)

Aggregations

EntityDescriptor (org.opensaml.saml.saml2.metadata.EntityDescriptor)22 IOException (java.io.IOException)11 InputStream (java.io.InputStream)9 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)9 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)9 Document (org.w3c.dom.Document)9 AssertionConsumerService (org.opensaml.saml.saml2.metadata.AssertionConsumerService)8 Element (org.w3c.dom.Element)8 CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)7 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)7 EntityIdCriterion (org.opensaml.core.criterion.EntityIdCriterion)7 XMLObject (org.opensaml.core.xml.XMLObject)7 SPSSODescriptor (org.opensaml.saml.saml2.metadata.SPSSODescriptor)7 X509Certificate (java.security.cert.X509Certificate)6 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)6 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)6 SamlRegisteredServiceCachingMetadataResolver (org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver)6 Test (org.junit.Test)6 IDPSSODescriptor (org.opensaml.saml.saml2.metadata.IDPSSODescriptor)6 SimpleSign (ddf.security.samlp.SimpleSign)5