org.opensaml.saml2.core.AuthnRequest Java Examples

The following examples show how to use org.opensaml.saml2.core.AuthnRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthnResponseEndpointSelector.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Selects the endpoint by way of the assertion consumer service index given in the AuthnRequest.
 * 
 * @param request the AuthnRequest
 * @param endpoints list of endpoints to select from
 * 
 * @return the selected endpoint
 */
protected Endpoint selectEndpointByACSIndex(AuthnRequest request, List<IndexedEndpoint> endpoints) {
    Integer acsIndex = request.getAssertionConsumerServiceIndex();
    for (IndexedEndpoint endpoint : endpoints) {
        if (endpoint == null || !getSupportedIssuerBindings().contains(endpoint.getBinding())) {
            log.debug(
                    "Endpoint '{}' with binding '{}' discarded because it requires an unsupported outbound binding.",
                    endpoint.getLocation(), endpoint.getBinding());
            continue;
        }

        if (DatatypeHelper.safeEquals(acsIndex, endpoint.getIndex())) {
            return endpoint;
        } else {
            log.debug("Endpoint '{}' with index '{}' discard because it does have the required index '{}'",
                    new Object[] {endpoint.getLocation(), endpoint.getIndex(), acsIndex});
        }
    }

    log.warn("Relying party '{}' requested the response to be returned to endpoint with ACS index '{}' "
            + "however no endpoint, with that index and using a supported binding, can be found "
            + " in the relying party's metadata ", getEntityMetadata().getEntityID(), acsIndex);
    return null;
}
 
Example #2
Source File: AuthnRequestUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    AuthnRequest req = (AuthnRequest) samlObject;

    if (attribute.getLocalName().equals(AuthnRequest.FORCE_AUTHN_ATTRIB_NAME)) {
        req.setForceAuthn(XSBooleanValue.valueOf(attribute.getValue()));
    } else if (attribute.getLocalName().equals(AuthnRequest.IS_PASSIVE_ATTRIB_NAME)) {
        req.setIsPassive(XSBooleanValue.valueOf(attribute.getValue()));
    } else if (attribute.getLocalName().equals(AuthnRequest.PROTOCOL_BINDING_ATTRIB_NAME)) {
        req.setProtocolBinding(attribute.getValue());
    } else if (attribute.getLocalName().equals(AuthnRequest.ASSERTION_CONSUMER_SERVICE_INDEX_ATTRIB_NAME)) {
        req.setAssertionConsumerServiceIndex(Integer.valueOf(attribute.getValue()));
    } else if (attribute.getLocalName().equals(AuthnRequest.ASSERTION_CONSUMER_SERVICE_URL_ATTRIB_NAME)) {
        req.setAssertionConsumerServiceURL(attribute.getValue());
    } else if (attribute.getLocalName().equals(AuthnRequest.ATTRIBUTE_CONSUMING_SERVICE_INDEX_ATTRIB_NAME)) {
        req.setAttributeConsumingServiceIndex(Integer.valueOf(attribute.getValue()));
    } else if (attribute.getLocalName().equals(AuthnRequest.PROVIDER_NAME_ATTRIB_NAME)) {
        req.setProviderName(attribute.getValue());
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example #3
Source File: AuthnRequestUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    AuthnRequest req = (AuthnRequest) parentSAMLObject;

    if (childSAMLObject instanceof Subject) {
        req.setSubject((Subject) childSAMLObject);
    } else if (childSAMLObject instanceof NameIDPolicy) {
        req.setNameIDPolicy((NameIDPolicy) childSAMLObject);
    } else if (childSAMLObject instanceof Conditions) {
        req.setConditions((Conditions) childSAMLObject);
    } else if (childSAMLObject instanceof RequestedAuthnContext) {
        req.setRequestedAuthnContext((RequestedAuthnContext) childSAMLObject);
    } else if (childSAMLObject instanceof Scoping) {
        req.setScoping((Scoping) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #4
Source File: AuthnResponseEndpointSelector.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Filters the list of possible endpoints by supported outbound bindings and, if the authentication request contains
 * a requested binding and not an ACS index, that too is used to filter the list.
 * 
 * @param endpoints raw list of endpoints
 * 
 * @return filtered endpoints
 */
protected List<? extends Endpoint> filterEndpointsByProtocolBinding(List<? extends Endpoint> endpoints) {
    log.debug("Filtering peer endpoints.  Supported peer endpoint bindings: {}", getSupportedIssuerBindings());
    AuthnRequest request = (AuthnRequest) getSamlRequest();

    boolean filterByRequestBinding = false;
    String acsBinding = DatatypeHelper.safeTrimOrNullString(request.getProtocolBinding());
    if (acsBinding != null && request.getAssertionConsumerServiceIndex() != null) {
        filterByRequestBinding = true;
    }

    List<Endpoint> filteredEndpoints = new ArrayList<Endpoint>(endpoints);
    Iterator<Endpoint> endpointItr = filteredEndpoints.iterator();
    Endpoint endpoint;
    while (endpointItr.hasNext()) {
        endpoint = endpointItr.next();
        if (!getSupportedIssuerBindings().contains(endpoint.getBinding())) {
            log.debug("Removing endpoint {} because its binding {} is not supported", endpoint.getLocation(),
                    endpoint.getBinding());
            endpointItr.remove();
            continue;
        }

        if (filterByRequestBinding && !endpoint.getBinding().equals(acsBinding)) {
            log.debug("Removing endpoint {} because its binding {} does not match request's requested binding",
                    endpoint.getLocation(), endpoint.getBinding());
            endpointItr.remove();
        }
    }

    return filteredEndpoints;
}
 
Example #5
Source File: SAMLUtilsTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildAuthnRequestObject() throws Exception {
    String consumerUrl = "http://someurl.com";
    String idpUrl = "http://idp.domain.example";
    String spId = "cloudstack";
    String authnId = SAMLUtils.generateSecureRandomId();
    AuthnRequest req = SAMLUtils.buildAuthnRequestObject(authnId, spId, idpUrl, consumerUrl);
    assertEquals(req.getAssertionConsumerServiceURL(), consumerUrl);
    assertEquals(req.getDestination(), idpUrl);
    assertEquals(req.getIssuer().getValue(), spId);
}
 
Example #6
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static AuthnRequest buildAuthnRequestObject(final String authnId, final String spId, final String idpUrl, final String consumerUrl) {
    // Issuer object
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(spId);

    // AuthnContextClass
    AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
    AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(
            SAMLConstants.SAML20_NS,
            "AuthnContextClassRef", "saml");
    authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);

    // AuthnContext
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
    RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

    // Creation of AuthRequestObject
    AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
    AuthnRequest authnRequest = authRequestBuilder.buildObject();
    authnRequest.setID(authnId);
    authnRequest.setDestination(idpUrl);
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setForceAuthn(false);
    authnRequest.setIsPassive(false);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    authnRequest.setAssertionConsumerServiceURL(consumerUrl);
    authnRequest.setProviderName(spId);
    authnRequest.setIssuer(issuer);
    authnRequest.setRequestedAuthnContext(requestedAuthnContext);

    return authnRequest;
}
 
Example #7
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static String buildAuthnRequestUrl(final String authnId, final SAMLProviderMetadata spMetadata, final SAMLProviderMetadata idpMetadata, final String signatureAlgorithm) {
    String redirectUrl = "";
    try {
        DefaultBootstrap.bootstrap();
        AuthnRequest authnRequest = SAMLUtils.buildAuthnRequestObject(authnId, spMetadata.getEntityId(), idpMetadata.getSsoUrl(), spMetadata.getSsoUrl());
        PrivateKey privateKey = null;
        if (spMetadata.getKeyPair() != null) {
            privateKey = spMetadata.getKeyPair().getPrivate();
        }
        redirectUrl = idpMetadata.getSsoUrl() + "?" + SAMLUtils.generateSAMLRequestSignature("SAMLRequest=" + SAMLUtils.encodeSAMLRequest(authnRequest), privateKey, signatureAlgorithm);
    } catch (ConfigurationException | FactoryConfigurationError | MarshallingException | IOException | NoSuchAlgorithmException | InvalidKeyException | java.security.SignatureException e) {
        s_logger.error("SAML AuthnRequest message building error: " + e.getMessage());
    }
    return redirectUrl;
}
 
Example #8
Source File: AuthReqBuilder.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Generate an authentication request.
 *
 * @return AuthnRequest Object
 * @throws Exception error when bootstrapping
 */
public AuthnRequest buildAuthenticationRequest(String issuerId) throws Exception {
    Util.doBootstrap();
    AuthnRequest authnRequest = (AuthnRequest) Util.buildXMLObject(AuthnRequest.DEFAULT_ELEMENT_NAME);
    authnRequest.setID(Util.createID());
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setIssuer(buildIssuer( issuerId));
    authnRequest.setNameIDPolicy(buildNameIDPolicy());
    return authnRequest;
}
 
Example #9
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Sign the SAML AuthnRequest message
 *
 * @param authnRequest
 * @param signatureAlgorithm
 * @param cred
 * @return
 * @throws org.wso2.carbon.identity.sso.agent.SSOAgentException
 */
public static AuthnRequest setSignature(AuthnRequest authnRequest, String signatureAlgorithm,
                                    X509Credential cred) throws SSOAgentException {
    doBootstrap();
    try {
        Signature signature = setSignatureRaw(signatureAlgorithm,cred);


        authnRequest.setSignature(signature);

        List<Signature> signatureList = new ArrayList<Signature>();
        signatureList.add(signature);

        // Marshall and Sign
        MarshallerFactory marshallerFactory =
                org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(authnRequest);

        marshaller.marshall(authnRequest);

        org.apache.xml.security.Init.init();
        Signer.signObjects(signatureList);
        return authnRequest;

    } catch (Exception e) {
        throw new SSOAgentException("Error while signing the SAML Request message", e);
    }
}
 
Example #10
Source File: SAMLSSOService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the SAMLRquest, the request can be the type AuthnRequest or
 * LogoutRequest. The SigAlg and Signature parameter will be used only with
 * the HTTP Redirect binding. With HTTP POST binding these values are null.
 * If the user already having a SSO session then the Response
 * will be returned if not only the validation results will be returned.
 *
 * @param samlReq
 * @param queryString
 * @param sessionId
 * @param rpSessionId
 * @param authnMode
 * @return
 * @throws IdentityException
 */
public SAMLSSOReqValidationResponseDTO validateSPInitSSORequest(String samlReq, String queryString,
                                                                String sessionId, String rpSessionId,
                                                                String authnMode, boolean isPost)
        throws IdentityException {
    XMLObject request;

    if (isPost) {
        request = SAMLSSOUtil.unmarshall(SAMLSSOUtil.decodeForPost(samlReq));
    } else {
        request = SAMLSSOUtil.unmarshall(SAMLSSOUtil.decode(samlReq));
    }

    if (request instanceof AuthnRequest) {
        SSOAuthnRequestValidator authnRequestValidator =
                SAMLSSOUtil.getSPInitSSOAuthnRequestValidator((AuthnRequest) request);
        SAMLSSOReqValidationResponseDTO validationResp = authnRequestValidator.validate();
        validationResp.setRequestMessageString(samlReq);
        validationResp.setQueryString(queryString);
        validationResp.setRpSessionId(rpSessionId);
        validationResp.setIdPInitSSO(false);

        return validationResp;
    } else if (request instanceof LogoutRequest) {
        SPInitLogoutRequestProcessor logoutReqProcessor = SAMLSSOUtil.getSPInitLogoutRequestProcessor();
        SAMLSSOReqValidationResponseDTO validationResponseDTO =
                logoutReqProcessor.process((LogoutRequest) request,
                        sessionId,
                        queryString);
        return validationResponseDTO;
    }

    return null;
}
 
Example #11
Source File: AuthenticationRequestBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Generate an authentication request with passive support.
 *
 * @return AuthnRequest Object
 * @throws Exception
 */
public AuthnRequest buildAuthenticationRequest(String subjectName, String nameIdPolicyFormat, boolean isPassive)
        throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Building Authentication Request");
    }
    Util.doBootstrap();
    AuthnRequest authnRequest = (AuthnRequest) Util
            .buildXMLObject(AuthnRequest.DEFAULT_ELEMENT_NAME);
    authnRequest.setID(Util.createID());
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setIssuer(buildIssuer());
    authnRequest.setNameIDPolicy(buildNameIDPolicy(nameIdPolicyFormat));
    authnRequest.setIsPassive(isPassive);
    authnRequest.setDestination(Util.getIdentityProviderSSOServiceURL());
    String acs = Util.getAssertionConsumerServiceURL();
    if (acs != null && acs.trim().length() > 0) {
        authnRequest.setAssertionConsumerServiceURL(acs);
    } else {
        authnRequest.setAssertionConsumerServiceURL(CarbonUIUtil.getAdminConsoleURL("").replace("carbon/", "acs"));
    }

    if (subjectName != null) {
        Subject subject = new SubjectBuilder().buildObject();
        NameID nameId = new NameIDBuilder().buildObject();
        nameId.setValue(subjectName);
        nameId.setFormat(NameIdentifier.EMAIL);
        subject.setNameID(nameId);
        authnRequest.setSubject(subject);

    }

    Util.setSignature(authnRequest, XMLSignature.ALGO_ID_SIGNATURE_RSA, new SignKeyDataHolder());

    return authnRequest;
}
 
Example #12
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected Extensions getSAMLExtensions(AuthnRequest inboundAuthnRequest) {
    
    Extensions extensions = null;
    Extensions oldExtensions = inboundAuthnRequest.getExtensions();
    if (oldExtensions != null) {
        ExtensionsBuilder extBuilder = new ExtensionsBuilder();
        extensions = extBuilder.buildObject(SAMLConstants.SAML20P_NS,
                Extensions.LOCAL_NAME, SAMLConstants.SAML20P_PREFIX);
        extensions.setDOM(oldExtensions.getDOM());
    }
    return extensions;
}
 
Example #13
Source File: AuthnRequestGenerator.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public AuthnRequest generateAuthnRequest(String destination, String responseLocation) {
	AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
	
	authnRequest.setAssertionConsumerServiceURL(responseLocation);
	authnRequest.setID(idService.generateID());
	authnRequest.setIssueInstant(timeService.getCurrentDateTime());
	authnRequest.setDestination(destination);
	
	authnRequest.setIssuer(issuerGenerator.generateIssuer());
	
	return authnRequest;
}
 
Example #14
Source File: AuthnRequestMarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException {
    AuthnRequest req = (AuthnRequest) samlObject;

    if (req.isForceAuthnXSBoolean() != null) {
        domElement.setAttributeNS(null, AuthnRequest.FORCE_AUTHN_ATTRIB_NAME, req.isForceAuthnXSBoolean()
                .toString());
    }

    if (req.isPassiveXSBoolean() != null) {
        domElement.setAttributeNS(null, AuthnRequest.IS_PASSIVE_ATTRIB_NAME, req.isPassiveXSBoolean().toString());
    }

    if (req.getProtocolBinding() != null) {
        domElement.setAttributeNS(null, AuthnRequest.PROTOCOL_BINDING_ATTRIB_NAME, req.getProtocolBinding());
    }

    if (req.getAssertionConsumerServiceIndex() != null) {
        domElement.setAttributeNS(null, AuthnRequest.ASSERTION_CONSUMER_SERVICE_INDEX_ATTRIB_NAME, req
                .getAssertionConsumerServiceIndex().toString());
    }

    if (req.getAssertionConsumerServiceURL() != null) {
        domElement.setAttributeNS(null, AuthnRequest.ASSERTION_CONSUMER_SERVICE_URL_ATTRIB_NAME, req
                .getAssertionConsumerServiceURL());
    }

    if (req.getAttributeConsumingServiceIndex() != null) {
        domElement.setAttributeNS(null, AuthnRequest.ATTRIBUTE_CONSUMING_SERVICE_INDEX_ATTRIB_NAME, req
                .getAttributeConsumingServiceIndex().toString());
    }

    if (req.getProviderName() != null) {
        domElement.setAttributeNS(null, AuthnRequest.PROVIDER_NAME_ATTRIB_NAME, req.getProviderName());
    }

    super.marshallAttributes(samlObject, domElement);
}
 
Example #15
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected Extensions getSAMLExtensions(HttpServletRequest request) {

        try {
            String samlRequest = request.getParameter(SSOConstants.HTTP_POST_PARAM_SAML2_AUTH_REQ);
            if (samlRequest == null) {
                samlRequest = (String) request.getAttribute(SSOConstants.HTTP_POST_PARAM_SAML2_AUTH_REQ);
            }

            if (samlRequest != null) {
                XMLObject xmlObject;
                if (SSOConstants.HTTP_POST.equals(request.getMethod())) {
                    xmlObject = unmarshall(SSOUtils.decodeForPost(samlRequest));
                } else {
                    xmlObject = unmarshall(SSOUtils.decode(samlRequest));
                }
                if (xmlObject instanceof AuthnRequest) {
                    AuthnRequest authnRequest = (AuthnRequest) xmlObject;
                    Extensions oldExtensions = authnRequest.getExtensions();
                    if (oldExtensions != null) {
                        ExtensionsBuilder extBuilder = new ExtensionsBuilder();
                        Extensions extensions = extBuilder.buildObject(SAMLConstants.SAML20P_NS,
                                Extensions.LOCAL_NAME, SAMLConstants.SAML20P_PREFIX);
                        extensions.setDOM(oldExtensions.getDOM());
                        return extensions;
                    }
                }
            }
        } catch (Exception e) { // TODO IDENTITY-2421
            //ignore
            log.debug("Error while loading SAML Extensions", e);
        }

        return null;
    }
 
Example #16
Source File: SAMLAuthnRequestValidator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public void setAuthnRequest(AuthnRequest authnRequest) {
    this.authnRequest = authnRequest;
}
 
Example #17
Source File: AuthnResponseEndpointSelector.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public Endpoint selectEndpoint() {
    if (getEntityRoleMetadata() == null) {
        log.debug("Unable to select endpoint, no entity role metadata available.");
        return null;
    }

    List<? extends Endpoint> endpoints = getEntityRoleMetadata().getEndpoints(getEndpointType());
    if (endpoints == null || endpoints.size() == 0) {
        return null;
    }

    Endpoint endpoint = null;
    AuthnRequest request = (AuthnRequest) getSamlRequest();
    if (request != null) {
        endpoints = filterEndpointsByProtocolBinding(endpoints);
        if (endpoints == null || endpoints.isEmpty()) {
            return null;
        }

        if (request.getAssertionConsumerServiceIndex() != null) {
            log.debug("Selecting endpoint by ACS index '{}' for request '{}' from entity '{}'", new Object[] {
                    request.getAssertionConsumerServiceIndex(), request.getID(), getEntityMetadata().getEntityID()});
            endpoint = selectEndpointByACSIndex(request, (List<IndexedEndpoint>) endpoints);
        } else if (request.getAssertionConsumerServiceURL() != null) {
            log.debug(
                    "Selecting endpoint by ACS URL '{}' and protocol binding '{}' for request '{}' from entity '{}'",
                    new Object[] {request.getAssertionConsumerServiceURL(), request.getProtocolBinding(),
                            request.getID(), getEntityMetadata().getEntityID()});
            endpoint = selectEndpointByACSURL(request, (List<IndexedEndpoint>) endpoints);
        }
    }

    if (endpoint == null && request.getAssertionConsumerServiceIndex() == null
            && request.getAssertionConsumerServiceURL() == null) {
        log.debug("No ACS index or URL given, selecting endpoint without additional constraints.");
        if (endpoints.get(0) instanceof IndexedEndpoint) {
            endpoint = selectIndexedEndpoint((List<IndexedEndpoint>) endpoints);
        } else {
            endpoint = selectNonIndexedEndpoint((List<Endpoint>) endpoints);
        }
    }

    return endpoint;
}
 
Example #18
Source File: AuthnResponseEndpointSelector.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Selects the endpoint by way of the assertion consumer service URL given in the AuthnRequest.
 * 
 * @param request the AuthnRequest
 * @param endpoints list of endpoints to select from
 * 
 * @return the selected endpoint
 */
protected Endpoint selectEndpointByACSURL(AuthnRequest request, List<IndexedEndpoint> endpoints) {
    String acsBinding = DatatypeHelper.safeTrimOrNullString(request.getProtocolBinding());

    for (IndexedEndpoint endpoint : endpoints) {
        if (!getSupportedIssuerBindings().contains(endpoint.getBinding())) {
            log.debug(
                    "Endpoint '{}' with binding '{}' discarded because that is not a supported outbound binding.",
                    endpoint.getLocation(), endpoint.getBinding());
            continue;
        }

        if (acsBinding != null) {
            if (!DatatypeHelper.safeEquals(acsBinding, endpoint.getBinding())) {
                log.debug(
                        "Endpoint '{}' with binding '{}' discarded because it does not meet protocol binding selection criteria",
                        endpoint.getLocation(), endpoint.getBinding());
                continue;
            }
        }

        String responseLocation = DatatypeHelper.safeTrim(endpoint.getResponseLocation());
        if (responseLocation != null){
                if(DatatypeHelper.safeEquals(responseLocation, request.getAssertionConsumerServiceURL())) {
                    return endpoint;
                }
        }else{    
            String location = DatatypeHelper.safeTrim(endpoint.getLocation());
            if (location != null && DatatypeHelper.safeEquals(location, request.getAssertionConsumerServiceURL())) {
                return endpoint;
            }
        }

        log.debug("Endpoint with Location '{}' discarded because neither its Location nor ResponseLocation match ACS URL '{}'",
                endpoint.getLocation(), request.getAssertionConsumerServiceURL());
    }

    log.warn("Relying party '{}' requested the response to be returned to endpoint with ACS URL '{}' "
            + " and binding '{}' however no endpoint, with that URL and using a supported binding, "
            + " can be found in the relying party's metadata ", new Object[] {getEntityMetadata().getEntityID(),
            request.getAssertionConsumerServiceURL(), (acsBinding == null) ? "any" : acsBinding});
    return null;
}
 
Example #19
Source File: AuthnRequestSchemaValidator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void validate(AuthnRequest request) throws ValidationException {
    super.validate(request);
}
 
Example #20
Source File: AuthnRequestBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public AuthnRequest buildObject() {
    return buildObject(SAMLConstants.SAML20P_NS, AuthnRequest.DEFAULT_ELEMENT_LOCAL_NAME,
            SAMLConstants.SAML20P_PREFIX);
}
 
Example #21
Source File: SAMLClient.java    From saml-sdk-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private String createAuthnRequest(String requestId)
    throws SAMLException
{
    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SAMLObjectBuilder<AuthnRequest> builder =
        (SAMLObjectBuilder<AuthnRequest>) builderFactory
        .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);

    SAMLObjectBuilder<Issuer> issuerBuilder =
        (SAMLObjectBuilder<Issuer>) builderFactory
        .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);

    AuthnRequest request = builder.buildObject();
    request.setAssertionConsumerServiceURL(spConfig.getAcs().toString());
    request.setDestination(idpConfig.getLoginUrl().toString());
    request.setIssueInstant(new DateTime());
    request.setID(requestId);

    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(spConfig.getEntityId());
    request.setIssuer(issuer);

    try {
        // samlobject to xml dom object
        Element elem = Configuration.getMarshallerFactory()
            .getMarshaller(request)
            .marshall(request);

        // and to a string...
        Document document = elem.getOwnerDocument();
        DOMImplementationLS domImplLS = (DOMImplementationLS) document
            .getImplementation();
        LSSerializer serializer = domImplLS.createLSSerializer();
        serializer.getDomConfig().setParameter("xml-declaration", false);
        return serializer.writeToString(elem);
    }
    catch (MarshallingException e) {
        throw new SAMLException(e);
    }
}
 
Example #22
Source File: AuthnRequestBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public AuthnRequest buildObject(String namespaceURI, String localName, String namespacePrefix) {
    return new AuthnRequestImpl(namespaceURI, localName, namespacePrefix);
}
 
Example #23
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected AuthnRequest buildAuthnRequest(HttpServletRequest request) throws SSOAgentException {

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer =
                issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion",
                        "Issuer", "samlp");
        issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());

		/* NameIDPolicy */
        NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
        NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
        nameIdPolicy.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
        nameIdPolicy.setSPNameQualifier("Issuer");
        nameIdPolicy.setAllowCreate(true);

		/* AuthnContextClass */
        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
        AuthnContextClassRef authnContextClassRef =
                authnContextClassRefBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion",
                        "AuthnContextClassRef",
                        "saml");
        authnContextClassRef.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

		/* AuthnContex */
        RequestedAuthnContextBuilder requestedAuthnContextBuilder =
                new RequestedAuthnContextBuilder();
        RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
        requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
        requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

        DateTime issueInstant = new DateTime();

		/* Creation of AuthRequestObject */
        AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
        AuthnRequest authRequest =
                authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
                        "AuthnRequest", "samlp");

        authRequest.setForceAuthn(ssoAgentConfig.getSAML2().isForceAuthn());
        authRequest.setIsPassive(ssoAgentConfig.getSAML2().isPassiveAuthn());
        authRequest.setIssueInstant(issueInstant);
        authRequest.setProtocolBinding(ssoAgentConfig.getSAML2().getHttpBinding());
        authRequest.setAssertionConsumerServiceURL(ssoAgentConfig.getSAML2().getACSURL());
        authRequest.setIssuer(issuer);
        authRequest.setNameIDPolicy(nameIdPolicy);
        authRequest.setRequestedAuthnContext(requestedAuthnContext);
        authRequest.setID(SSOAgentUtils.createID());
        authRequest.setVersion(SAMLVersion.VERSION_20);
        authRequest.setDestination(ssoAgentConfig.getSAML2().getIdPURL());
        if (request.getAttribute(Extensions.LOCAL_NAME) != null) {
            authRequest.setExtensions((Extensions) request.getAttribute(Extensions.LOCAL_NAME));
        }

		/* Requesting Attributes. This Index value is registered in the IDP */
        if (ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex() != null &&
                ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex().trim().length() > 0) {
            authRequest.setAttributeConsumingServiceIndex(Integer.parseInt(
                    ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex()));
        }

        return authRequest;
    }
 
Example #24
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Handles the request for http post binding
 *
 * @param request  The HTTP request with SAML2 message
 * @param response The HTTP response
 * @param isLogout Whether the request is a logout request
 * @throws SSOAgentException
 */
public String buildPostRequest(HttpServletRequest request, HttpServletResponse response,
                               boolean isLogout) throws SSOAgentException {

    RequestAbstractType requestMessage = null;
    if (!isLogout) {
        requestMessage = buildAuthnRequest(request);
        if (ssoAgentConfig.getSAML2().isRequestSigned()) {
            requestMessage = SSOAgentUtils.setSignature((AuthnRequest) requestMessage,
                    XMLSignature.ALGO_ID_SIGNATURE_RSA,
                    new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential()));
        }

    } else {
        LoggedInSessionBean sessionBean = (LoggedInSessionBean) request.getSession(false).
                getAttribute(SSOAgentConstants.SESSION_BEAN_NAME);
        if (sessionBean != null) {
            requestMessage = buildLogoutRequest(sessionBean.getSAML2SSO()
                    .getSubjectId(), sessionBean.getSAML2SSO().getSessionIndex());
            if (ssoAgentConfig.getSAML2().isRequestSigned()) {
                requestMessage = SSOAgentUtils.setSignature((LogoutRequest) requestMessage,
                        XMLSignature.ALGO_ID_SIGNATURE_RSA,
                        new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential()));
            }
        } else {
            throw new SSOAgentException("SLO Request can not be built. SSO Session is null");
        }
    }
    String encodedRequestMessage = encodeRequestMessage(requestMessage, SAMLConstants.SAML2_POST_BINDING_URI);

    Map<String, String[]> paramsMap = new HashMap<String, String[]>();
    paramsMap.put(SSOAgentConstants.SAML2SSO.HTTP_POST_PARAM_SAML2_AUTH_REQ,
            new String[]{encodedRequestMessage});
    if (ssoAgentConfig.getSAML2().getRelayState() != null) {
        paramsMap.put(RelayState.DEFAULT_ELEMENT_LOCAL_NAME,
                new String[]{ssoAgentConfig.getSAML2().getRelayState()});
    }

    //Add any additional parameters defined
    if (ssoAgentConfig.getQueryParams() != null && !ssoAgentConfig.getQueryParams().isEmpty()) {
        paramsMap.putAll(ssoAgentConfig.getQueryParams());
    }

    StringBuilder htmlParams = new StringBuilder();
    for (Map.Entry<String, String[]> entry : paramsMap.entrySet()) {
        if (entry.getKey() != null && entry.getValue() != null && entry.getValue().length > 0) {
            for (String param : entry.getValue()) {
                htmlParams.append("<input type='hidden' name='").append(entry.getKey())
                        .append("' value='").append(param).append("'>\n");
            }
        }

    }
    String htmlPayload = ssoAgentConfig.getSAML2().getPostBindingRequestHTMLPayload();
    if (htmlPayload == null || !htmlPayload.contains("<!--$saml_params-->")) {
        htmlPayload = "<html>\n" +
                "<body>\n" +
                "<p>You are now redirected back to " + ssoAgentConfig.getSAML2().getIdPURL() + " \n" +
                "If the redirection fails, please click the post button.</p>\n" +
                "<form method='post' action='" + ssoAgentConfig.getSAML2().getIdPURL() + "'>\n" +
                "<p>\n" +
                htmlParams.toString() +
                "<button type='submit'>POST</button>\n" +
                "</p>\n" +
                "</form>\n" +
                "<script type='text/javascript'>\n" +
                "document.forms[0].submit();\n" +
                "</script>\n" +
                "</body>\n" +
                "</html>";
    } else {
        htmlPayload = htmlPayload.replace("<!--$saml_params-->",
                htmlParams.toString());
    }
    return htmlPayload;

}
 
Example #25
Source File: SAMLAuthnRequestValidator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public AuthnRequest getAuthnRequest() {
    return authnRequest;
}
 
Example #26
Source File: SAMLAuthnRequestValidator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public SAMLAuthnRequestValidator(AuthnRequest authnRequest) {
    this.setAuthnRequest(authnRequest);
}
 
Example #27
Source File: SPInitSSOAuthnRequestValidator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public SPInitSSOAuthnRequestValidator(AuthnRequest authnReq) throws IdentityException {
    this.authnReq = authnReq;
}
 
Example #28
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private RequestedAuthnContext buildRequestedAuthnContext(AuthnRequest inboundAuthnRequest) throws SAMLSSOException {
    
    /* AuthnContext */
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = null;
    RequestedAuthnContext requestedAuthnContext = null;
    
    String includeAuthnContext = properties
            .get(IdentityApplicationConstants.Authenticator.SAML2SSO.INCLUDE_AUTHN_CONTEXT);
    
    if (StringUtils.isNotEmpty(includeAuthnContext) && "as_request".equalsIgnoreCase(includeAuthnContext)) {
        if (inboundAuthnRequest != null) {
            RequestedAuthnContext incomingRequestedAuthnContext = inboundAuthnRequest.getRequestedAuthnContext();
            if (incomingRequestedAuthnContext != null) {
                requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
                requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
                requestedAuthnContext.setDOM(incomingRequestedAuthnContext.getDOM());
            }
        }
    } else if (StringUtils.isEmpty(includeAuthnContext) || "yes".equalsIgnoreCase(includeAuthnContext)) {
        requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
        requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
        /* AuthnContextClass */
        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
        AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder
                .buildObject(SAMLConstants.SAML20_NS,
                        AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME,
                        SAMLConstants.SAML20_PREFIX);

        String authnContextClassProp = properties
                .get(IdentityApplicationConstants.Authenticator.SAML2SSO.AUTHENTICATION_CONTEXT_CLASS);

        if (StringUtils.isNotEmpty(authnContextClassProp)) {
            authnContextClassRef.setAuthnContextClassRef(IdentityApplicationManagementUtil
                    .getSAMLAuthnContextClasses().get(authnContextClassProp));
        } else {
            authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);
        }

        /* Authentication Context Comparison Level */
        String authnContextComparison = properties
                .get(IdentityApplicationConstants.Authenticator.SAML2SSO.AUTHENTICATION_CONTEXT_COMPARISON_LEVEL);

        if (StringUtils.isNotEmpty(authnContextComparison)) {
            if (AuthnContextComparisonTypeEnumeration.EXACT.toString().equalsIgnoreCase(
                    authnContextComparison)) {
                requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
            } else if (AuthnContextComparisonTypeEnumeration.MINIMUM.toString().equalsIgnoreCase(
                    authnContextComparison)) {
                requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM);
            } else if (AuthnContextComparisonTypeEnumeration.MAXIMUM.toString().equalsIgnoreCase(
                    authnContextComparison)) {
                requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.MAXIMUM);
            } else if (AuthnContextComparisonTypeEnumeration.BETTER.toString().equalsIgnoreCase(
                    authnContextComparison)) {
                requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.BETTER);
            }
        } else {
            requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
        }
        requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
    }
    return requestedAuthnContext;
}
 
Example #29
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private AuthnRequest buildAuthnRequest(HttpServletRequest request,
                                         boolean isPassive, String idpUrl, AuthenticationContext context) throws SAMLSSOException {

      IssuerBuilder issuerBuilder = new IssuerBuilder();
      Issuer issuer = issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp");

      String spEntityId = properties.get(IdentityApplicationConstants.Authenticator.SAML2SSO.SP_ENTITY_ID);

      if (spEntityId != null && !spEntityId.isEmpty()) {
          issuer.setValue(spEntityId);
      } else {
          issuer.setValue("carbonServer");
      }

      DateTime issueInstant = new DateTime();

/* Creation of AuthRequestObject */
      AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
      AuthnRequest authRequest = authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
              "AuthnRequest", "samlp");
      authRequest.setForceAuthn(isForceAuthenticate(context));
      authRequest.setIsPassive(isPassive);
      authRequest.setIssueInstant(issueInstant);

String includeProtocolBindingProp = properties
              .get(IdentityApplicationConstants.Authenticator.SAML2SSO.INCLUDE_PROTOCOL_BINDING);
      if (StringUtils.isEmpty(includeProtocolBindingProp) || Boolean.parseBoolean(includeProtocolBindingProp)) {
          authRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
      }

      String acsUrl = null;
      AuthenticatorConfig authenticatorConfig =
              FileBasedConfigurationBuilder.getInstance().getAuthenticatorConfigMap()
                      .get(SSOConstants.AUTHENTICATOR_NAME);
      if (authenticatorConfig != null){
          String tmpAcsUrl = authenticatorConfig.getParameterMap().get(SSOConstants.ServerConfig.SAML_SSO_ACS_URL);
          if(StringUtils.isNotBlank(tmpAcsUrl)){
              acsUrl = tmpAcsUrl;
          }
      }

      if(acsUrl == null) {
          acsUrl = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, true, true);
      }

      authRequest.setAssertionConsumerServiceURL(acsUrl);
      authRequest.setIssuer(issuer);
      authRequest.setID(SSOUtils.createID());
      authRequest.setVersion(SAMLVersion.VERSION_20);
      authRequest.setDestination(idpUrl);

String attributeConsumingServiceIndexProp = properties
              .get(IdentityApplicationConstants.Authenticator.SAML2SSO.ATTRIBUTE_CONSUMING_SERVICE_INDEX);
      if (StringUtils.isNotEmpty(attributeConsumingServiceIndexProp)) {
          try {	
              authRequest.setAttributeConsumingServiceIndex(Integer
                      .valueOf(attributeConsumingServiceIndexProp));
          } catch (NumberFormatException e) {
              log.error(
                      "Error while populating SAMLRequest with AttributeConsumingServiceIndex: "
                              + attributeConsumingServiceIndexProp, e);
          }
      }
      
      String includeNameIDPolicyProp = properties
              .get(IdentityApplicationConstants.Authenticator.SAML2SSO.INCLUDE_NAME_ID_POLICY);
      if (StringUtils.isEmpty(includeNameIDPolicyProp) || Boolean.parseBoolean(includeNameIDPolicyProp)) {
          NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
          NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
          nameIdPolicy.setFormat(NameIDType.UNSPECIFIED);
          //nameIdPolicy.setSPNameQualifier("Issuer");
          nameIdPolicy.setAllowCreate(true);
          authRequest.setNameIDPolicy(nameIdPolicy);
      }

//Get the inbound SAMLRequest
      AuthnRequest inboundAuthnRequest = getAuthnRequest(context);
      
      RequestedAuthnContext requestedAuthnContext = buildRequestedAuthnContext(inboundAuthnRequest);
      if (requestedAuthnContext != null) {
          authRequest.setRequestedAuthnContext(requestedAuthnContext);
      }

      Extensions extensions = getSAMLExtensions(request);
      if (extensions != null) {
          authRequest.setExtensions(extensions);
      }

      return authRequest;
  }
 
Example #30
Source File: AuthenticationRequestBuilder.java    From carbon-identity with Apache License 2.0 2 votes vote down vote up
/**
 * Generate an authentication request.
 *
 * @return AuthnRequest Object
 * @throws Exception
 */
public AuthnRequest buildAuthenticationRequest(String subjectName, String nameIdPolicyFormat)
        throws Exception {
    return buildAuthenticationRequest(subjectName, nameIdPolicyFormat, false);
}