org.opensaml.saml.common.SAMLVersion Java Examples

The following examples show how to use org.opensaml.saml.common.SAMLVersion. 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: AbstractSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Create a new SAML response object.
 * @param id the id
 * @param issueInstant the issue instant
 * @param recipient the recipient
 * @param service the service
 * @return the response
 */
public Response newResponse(final String id, final DateTime issueInstant,
                            final String recipient, final WebApplicationService service) {

    final Response samlResponse = newSamlObject(Response.class);
    samlResponse.setID(id);
    samlResponse.setIssueInstant(issueInstant);
    samlResponse.setVersion(SAMLVersion.VERSION_20);
    if (service instanceof SamlService) {
        final SamlService samlService = (SamlService) service;

        final String requestId = samlService.getRequestID();
        if (StringUtils.isNotBlank(requestId)) {
            samlResponse.setInResponseTo(requestId);
        }
    }
    return samlResponse;
}
 
Example #2
Source File: SAML2PResponseComponentBuilder.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public static LogoutResponse createSAMLLogoutResponse(
    String inResponseTo,
    String issuer,
    Status status,
    String destination
) {
    if (logoutResponseBuilder == null) {
        logoutResponseBuilder = (SAMLObjectBuilder<LogoutResponse>)
            builderFactory.getBuilder(LogoutResponse.DEFAULT_ELEMENT_NAME);
    }
    LogoutResponse response = logoutResponseBuilder.buildObject();

    response.setID(UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(inResponseTo);
    response.setIssuer(createIssuer(issuer));
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);
    response.setDestination(destination);

    return response;
}
 
Example #3
Source File: SAML2PResponseComponentBuilder.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Response createSAMLResponse(
    String inResponseTo,
    Issuer issuer,
    Status status
) {
    if (responseBuilder == null) {
        responseBuilder = (SAMLObjectBuilder<Response>)
            builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
    }
    Response response = responseBuilder.buildObject();

    response.setID(UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(inResponseTo);
    response.setIssuer(issuer);
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);

    return response;
}
 
Example #4
Source File: SAML2PResponseComponentBuilder.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public static LogoutResponse createSAMLLogoutResponse(
    String inResponseTo,
    String issuer,
    Status status,
    String destination
) {
    if (logoutResponseBuilder == null) {
        logoutResponseBuilder = (SAMLObjectBuilder<LogoutResponse>)
            builderFactory.getBuilder(LogoutResponse.DEFAULT_ELEMENT_NAME);
    }
    LogoutResponse response = logoutResponseBuilder.buildObject();

    response.setID("_" + UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(inResponseTo);
    response.setIssuer(createIssuer(issuer));
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);
    response.setDestination(destination);

    return response;
}
 
Example #5
Source File: SAML2PResponseComponentBuilder.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Response createSAMLResponse(
    String inResponseTo,
    String issuer,
    Status status
) {
    if (responseBuilder == null) {
        responseBuilder = (SAMLObjectBuilder<Response>)
            builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
    }
    Response response = responseBuilder.buildObject();

    response.setID("_" + UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(inResponseTo);
    response.setIssuer(createIssuer(issuer));
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);

    return response;
}
 
Example #6
Source File: SAML2PResponseComponentBuilder.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Response createSAMLResponse(
    String inResponseTo,
    String issuer,
    Status status
) {
    if (responseBuilder == null) {
        responseBuilder = (SAMLObjectBuilder<Response>)
            builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
    }
    Response response = responseBuilder.buildObject();

    response.setID("_" + UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(inResponseTo);
    response.setIssuer(createIssuer(issuer));
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);

    return response;
}
 
Example #7
Source File: SAML2PResponseComponentBuilder.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Response createSAMLResponse(
    String inResponseTo,
    String issuer,
    Status status
) {
    if (responseBuilder == null) {
        responseBuilder = (SAMLObjectBuilder<Response>)
            builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
    }
    Response response = responseBuilder.buildObject();

    response.setID(UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(inResponseTo);
    response.setIssuer(createIssuer(issuer));
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);

    return response;
}
 
Example #8
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCreateLogoutRequest() throws Exception {
    Document doc = DOMUtils.createDocument();

    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer("http://localhost:9001/app");

    NameIDBean nameIdBean = new NameIDBean();
    nameIdBean.setNameValue("uid=joe,ou=people,ou=saml-demo,o=example.com");
    nameIdBean.setNameQualifier("www.example.com");
    NameID nameID = SAML2ComponentBuilder.createNameID(nameIdBean);

    Date notOnOrAfter = new Date();
    notOnOrAfter.setTime(notOnOrAfter.getTime() + 60L * 1000L);
    LogoutRequest logoutRequest =
        SamlpRequestComponentBuilder.createLogoutRequest(SAMLVersion.VERSION_20, issuer, null, null,
                                                         notOnOrAfter, null, nameID);

    Element policyElement = OpenSAMLUtil.toDom(logoutRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example #9
Source File: SamlTokenPolicyValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Check the policy version against the received assertion
 */
private boolean checkVersion(
    AssertionInfoMap aim,
    SamlToken samlToken,
    SamlAssertionWrapper assertionWrapper
) {
    SamlTokenType samlTokenType = samlToken.getSamlTokenType();
    if ((samlTokenType == SamlTokenType.WssSamlV11Token10
        || samlTokenType == SamlTokenType.WssSamlV11Token11)
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_11) {
        return false;
    } else if (samlTokenType == SamlTokenType.WssSamlV20Token11
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_20) {
        return false;
    }

    if (samlTokenType != null) {
        PolicyUtils.assertPolicy(aim, new QName(samlToken.getVersion().getNamespace(), samlTokenType.name()));
    }
    return true;
}
 
Example #10
Source File: SamlTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Check the policy version against the received assertion
 */
private boolean checkVersion(
    AssertionInfoMap aim,
    SamlToken samlToken,
    SamlAssertionWrapper assertionWrapper
) {
    SamlTokenType tokenType = samlToken.getSamlTokenType();
    if ((tokenType == SamlTokenType.WssSamlV11Token10
        || tokenType == SamlTokenType.WssSamlV11Token11)
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_11) {
        return false;
    } else if (tokenType == SamlTokenType.WssSamlV20Token11
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_20) {
        return false;
    }
    PolicyUtils.assertPolicy(aim, new QName(samlToken.getVersion().getNamespace(), tokenType.name()));
    return true;
}
 
Example #11
Source File: AuthReqBuilder.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Generate an Signed authentication request with a custom consumer url.
 *
 * @return AuthnRequest Object
 * @throws SSOHostObjectException error when bootstrapping
 */

public AuthnRequest buildSignedAuthRequest(String issuerId, String destination, String acsUrl, boolean isPassive,
        int tenantId, String tenantDomain, String nameIdPolicy) throws SSOHostObjectException {
    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(Util.buildNameIDPolicy(nameIdPolicy));
    if (!StringUtils.isEmpty(acsUrl)) {
        acsUrl = Util.processAcsUrl(acsUrl);
        authnRequest.setAssertionConsumerServiceURL(acsUrl);
    }
    if (isPassive){
        authnRequest.setIsPassive(true);
    }
    authnRequest.setDestination(destination);
    SSOAgentCarbonX509Credential ssoAgentCarbonX509Credential =
            new SSOAgentCarbonX509Credential(tenantId, tenantDomain);
    setSignature(authnRequest, SignatureConstants.ALGO_ID_SIGNATURE_RSA,
            new X509CredentialImpl(ssoAgentCarbonX509Credential));
    return authnRequest;
}
 
Example #12
Source File: Saml10ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Create a new SAML response object.
 * @param id the id
 * @param issueInstant the issue instant
 * @param recipient the recipient
 * @param service the service
 * @return the response
 */
public Response newResponse(final String id, final DateTime issueInstant,
                                     final String recipient, final WebApplicationService service) {

    final Response samlResponse = newSamlObject(Response.class);
    samlResponse.setID(id);
    samlResponse.setIssueInstant(issueInstant);
    samlResponse.setVersion(SAMLVersion.VERSION_11);
    samlResponse.setInResponseTo(recipient);
    if (service instanceof SamlService) {
        final SamlService samlService = (SamlService) service;

        final String requestId = samlService.getRequestID();
        if (StringUtils.isNotBlank(requestId)) {
            samlResponse.setInResponseTo(requestId);
        }
    }
    return samlResponse;
}
 
Example #13
Source File: VerifyAssertionTranslator.java    From verify-service-provider with MIT License 6 votes vote down vote up
public void validateIdpAssertion(Assertion assertion, String expectedInResponseTo, QName role) {

        if (assertion.getIssueInstant() == null) {
            throw new SamlResponseValidationException("Assertion IssueInstant is missing.");
        }

        if (assertion.getID() == null || assertion.getID().length() == 0) {
            throw new SamlResponseValidationException("Assertion Id is missing or blank.");
        }

        if (assertion.getIssuer() == null || assertion.getIssuer().getValue() == null || assertion.getIssuer().getValue().length() == 0) {
            throw new SamlResponseValidationException("Assertion with id " + assertion.getID() + " has missing or blank Issuer.");
        }

        if (assertion.getVersion() == null) {
            throw new SamlResponseValidationException("Assertion with id " + assertion.getID() + " has missing Version.");
        }

        if (!assertion.getVersion().equals(SAMLVersion.VERSION_20)) {
            throw new SamlResponseValidationException("Assertion with id " + assertion.getID() + " declared an illegal Version attribute value.");
        }

        assertionsSignatureValidator.validate(singletonList(assertion), role);
        subjectValidator.validate(assertion.getSubject(), expectedInResponseTo);
        attributeStatementValidator.validate(assertion);
    }
 
Example #14
Source File: AuthReqBuilder.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Generate an authentication request.
 *
 * @return AuthnRequest Object
 * @throws SSOHostObjectException error when bootstrapping
 */
public AuthnRequest buildAuthenticationRequest(String issuerId, String acsUrl, boolean isPassive,
        String nameIdPolicy) throws SSOHostObjectException {
    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(Util.buildNameIDPolicy(nameIdPolicy));
    if (isPassive){
        authnRequest.setIsPassive(true);
    }
    if (!StringUtils.isEmpty(acsUrl)) {
        acsUrl = Util.processAcsUrl(acsUrl);
        authnRequest.setAssertionConsumerServiceURL(acsUrl);
    }
    return authnRequest;
}
 
Example #15
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCreateAuthnRequest() throws Exception {
    Document doc = DOMUtils.createDocument();

    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer("http://localhost:9001/app");
    NameIDPolicy nameIDPolicy =
        SamlpRequestComponentBuilder.createNameIDPolicy(
            true, "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent", "Issuer"
        );

    AuthnContextClassRef authnCtxClassRef =
        SamlpRequestComponentBuilder.createAuthnCtxClassRef(
            "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
        );
    RequestedAuthnContext authnCtx =
        SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT,
            Collections.singletonList(authnCtxClassRef), null
        );

    AuthnRequest authnRequest =
        SamlpRequestComponentBuilder.createAuthnRequest(
            "http://localhost:9001/sso", false, false,
            "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", SAMLVersion.VERSION_20,
            issuer, nameIDPolicy, authnCtx
        );

    Element policyElement = OpenSAMLUtil.toDom(authnRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example #16
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private String createSamlAuthResponse(AuthnRequest authnRequest) {
    try {
        Response response = createSamlElement(Response.class);
        response.setID(nextId());

        if (authnRequest != null) {
            response.setInResponseTo(authnRequest.getID());
        }

        response.setVersion(SAMLVersion.VERSION_20);
        response.setStatus(createStatus(StatusCode.SUCCESS));
        response.setIssueInstant(new DateTime());

        Assertion assertion = createSamlElement(Assertion.class);
        response.getAssertions().add(assertion);

        assertion.setID(nextId());
        assertion.setIssueInstant(new DateTime());
        assertion.setIssuer(createIssuer());

        AuthnStatement authnStatement = createSamlElement(AuthnStatement.class);
        assertion.getAuthnStatements().add(authnStatement);

        authnStatement.setAuthnInstant(new DateTime());
        authnStatement.setSessionIndex(nextId());
        authnStatement.setAuthnContext(createAuthnCotext());

        Subject subject = createSamlElement(Subject.class);
        assertion.setSubject(subject);

        subject.setNameID(createNameID(NameIDType.UNSPECIFIED, authenticateUser));

        if (authnRequest != null) {
            subject.getSubjectConfirmations()
                    .add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                            new DateTime().plusMinutes(1), authnRequest.getID(),
                            authnRequest.getAssertionConsumerServiceURL()));
        } else {
            subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                    new DateTime().plusMinutes(1), null, defaultAssertionConsumerService));
        }

        Conditions conditions = createSamlElement(Conditions.class);
        assertion.setConditions(conditions);

        conditions.setNotBefore(new DateTime());
        conditions.setNotOnOrAfter(new DateTime().plusMinutes(1));

        if (authenticateUserRoles != null) {
            AttributeStatement attributeStatement = createSamlElement(AttributeStatement.class);
            assertion.getAttributeStatements().add(attributeStatement);

            Attribute attribute = createSamlElement(Attribute.class);
            attributeStatement.getAttributes().add(attribute);

            attribute.setName("roles");
            attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

            for (String role : authenticateUserRoles) {
                attribute.getAttributeValues().add(createXSAny(AttributeValue.DEFAULT_ELEMENT_NAME, role));
            }
        }

        if (signResponses) {
            Signature signature = createSamlElement(Signature.class);
            assertion.setSignature(signature);

            signature.setSigningCredential(this.signingCredential);
            signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
            signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);

            Signer.signObject(signature);
        }

        String marshalledXml = marshallSamlXml(response);

        return Base64Support.encode(marshalledXml.getBytes("UTF-8"), Base64Support.UNCHUNKED);

    } catch (MarshallingException | SignatureException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: CustomSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Create a SAML 2.0 Protocol AuthnRequest
 */
public AuthnRequest createAuthnRequest(
    String issuerId,
    String assertionConsumerServiceAddress
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameIDPolicy nameIDPolicy =
        SamlpRequestComponentBuilder.createNameIDPolicy(
            true, "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent", issuerId
        );

    AuthnContextClassRef authnCtxClassRef =
        SamlpRequestComponentBuilder.createAuthnCtxClassRef(
            "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
        );
    RequestedAuthnContext authnCtx =
        SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT,
            Collections.singletonList(authnCtxClassRef), null
        );

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createAuthnRequest(
            assertionConsumerServiceAddress,
            forceAuthn,
            isPassive,
            protocolBinding,
            SAMLVersion.VERSION_11,
            issuer,
            nameIDPolicy,
            authnCtx
    );

}
 
Example #18
Source File: DefaultSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Create a SAML 2.0 Protocol AuthnRequest
 */
public AuthnRequest createAuthnRequest(
    String issuerId,
    String assertionConsumerServiceAddress
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameIDPolicy nameIDPolicy =
        SamlpRequestComponentBuilder.createNameIDPolicy(
            true, nameIDFormat, issuerId
        );

    AuthnContextClassRef authnCtxClassRef =
        SamlpRequestComponentBuilder.createAuthnCtxClassRef(
            "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
        );
    RequestedAuthnContext authnCtx =
        SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT,
            Collections.singletonList(authnCtxClassRef), null
        );

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createAuthnRequest(
            assertionConsumerServiceAddress,
            forceAuthn,
            isPassive,
            protocolBinding,
            SAMLVersion.VERSION_20,
            issuer,
            nameIDPolicy,
            authnCtx
    );

}
 
Example #19
Source File: SamlpRequestComponentBuilder.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
//CHECKSTYLE:OFF
public static AuthnRequest createAuthnRequest(
    String serviceURL,
    boolean forceAuthn,
    boolean isPassive,
    String protocolBinding,
    SAMLVersion version,
    Issuer issuer,
    NameIDPolicy nameIDPolicy,
    RequestedAuthnContext requestedAuthnCtx
) {
//CHECKSTYLE:ON
    if (authnRequestBuilder == null) {
        authnRequestBuilder = (SAMLObjectBuilder<AuthnRequest>)
            builderFactory.getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    }
    AuthnRequest authnRequest = authnRequestBuilder.buildObject();
    authnRequest.setAssertionConsumerServiceURL(serviceURL);
    authnRequest.setForceAuthn(forceAuthn);
    authnRequest.setID("_" + UUID.randomUUID().toString());
    authnRequest.setIsPassive(isPassive);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setProtocolBinding(protocolBinding);
    authnRequest.setVersion(version);

    authnRequest.setIssuer(issuer);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    authnRequest.setRequestedAuthnContext(requestedAuthnCtx);

    return authnRequest;
}
 
Example #20
Source File: SAMLTokenValidator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Check the Conditions of the Assertion.
 */
protected boolean isConditionValid(SamlAssertionWrapper assertion, int maxClockSkew) throws WSSecurityException {
    DateTime validFrom = null;
    DateTime validTill = null;
    if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)
        && assertion.getSaml2().getConditions() != null) {
        validFrom = assertion.getSaml2().getConditions().getNotBefore();
        validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
    } else if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_11)
        && assertion.getSaml1().getConditions() != null) {
        validFrom = assertion.getSaml1().getConditions().getNotBefore();
        validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
    }

    if (validFrom != null) {
        DateTime currentTime = new DateTime();
        currentTime = currentTime.plusSeconds(maxClockSkew);
        if (validFrom.isAfter(currentTime)) {
            LOG.debug("SAML Token condition (Not Before) not met");
            return false;
        }
    }

    if (validTill != null && validTill.isBeforeNow()) {
        LOG.debug("SAML Token condition (Not On Or After) not met");
        return false;
    }
    return true;
}
 
Example #21
Source File: SAMLTokenValidator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Instant getCreated(SamlAssertionWrapper assertion) {
    DateTime validFrom = null;
    if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
        validFrom = assertion.getSaml2().getConditions().getNotBefore();
    } else {
        validFrom = assertion.getSaml1().getConditions().getNotBefore();
    }

    if (validFrom == null) {
        return null;
    }
    return validFrom.toDate().toInstant();
}
 
Example #22
Source File: SAMLTokenValidator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Instant getExpires(SamlAssertionWrapper assertion) {
    DateTime validTill = null;
    if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
        validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
    } else {
        validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
    }

    if (validTill == null) {
        return null;
    }
    return validTill.toDate().toInstant();
}
 
Example #23
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfAssertionVersionInvalidWhenValidatingIdpAssertion() {
    Assertion assertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), "requestId").buildUnencrypted();
    assertion.setVersion(SAMLVersion.VERSION_10);

    exception.expect(SamlResponseValidationException.class);
    exception.expectMessage("Assertion with id mds-assertion declared an illegal Version attribute value.");
    verifyAssertionService.validateIdpAssertion(assertion, "not-used", IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
}
 
Example #24
Source File: ResponseSchemaValidator.java    From saml-client with MIT License 5 votes vote down vote up
private void validateVersion(StatusResponseType response) throws SamlException {
  if (response.getVersion() == null) {
    throw new SamlException("Version attribute must not be null");
  }
  if (!Objects.equals(response.getVersion().toString(), SAMLVersion.VERSION_20.toString())) {
    throw new SamlException("Wrong SAML Version");
  }
}
 
Example #25
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/** Create a minimal SAML request
 *
 * @param defaultElementName The SomeClass.DEFAULT_ELEMENT_NAME we'll be casting this object into
 * */
private RequestAbstractType getBasicSamlRequest(QName defaultElementName) {
  RequestAbstractType request = (RequestAbstractType) buildSamlObject(defaultElementName);
  request.setID("z" + UUID.randomUUID().toString()); // ADFS needs IDs to start with a letter

  request.setVersion(SAMLVersion.VERSION_20);
  request.setIssueInstant(DateTime.now());

  Issuer issuer = (Issuer) buildSamlObject(Issuer.DEFAULT_ELEMENT_NAME);
  issuer.setValue(relyingPartyIdentifier);
  request.setIssuer(issuer);

  return request;
}
 
Example #26
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Gets saml logout response.
 *
 * @param status  the status code @See StatusCode.java
 * @param statMsg the status message
 * @return saml logout response
 * @throws SamlException the saml exception
 */
public String getSamlLogoutResponse(final String status, final String statMsg)
    throws SamlException {
  LogoutResponse response = (LogoutResponse) buildSamlObject(LogoutResponse.DEFAULT_ELEMENT_NAME);
  response.setID("z" + UUID.randomUUID().toString()); // ADFS needs IDs to start with a letter

  response.setVersion(SAMLVersion.VERSION_20);
  response.setIssueInstant(DateTime.now());

  Issuer issuer = (Issuer) buildSamlObject(Issuer.DEFAULT_ELEMENT_NAME);
  issuer.setValue(relyingPartyIdentifier);
  response.setIssuer(issuer);

  //Status
  Status stat = (Status) buildSamlObject(Status.DEFAULT_ELEMENT_NAME);
  StatusCode statCode = new StatusCodeBuilder().buildObject();
  statCode.setValue(status);
  stat.setStatusCode(statCode);
  if (statMsg != null) {
    StatusMessage statMessage = new StatusMessageBuilder().buildObject();
    statMessage.setMessage(statMsg);
    stat.setStatusMessage(statMessage);
  }
  response.setStatus(stat);
  //Add a signature into the response
  signSAMLObject(response);

  StringWriter stringWriter;
  try {
    stringWriter = marshallXmlObject(response);
  } catch (MarshallingException ex) {
    throw new SamlException("Error while marshalling SAML request to XML", ex);
  }

  logger.trace("Issuing SAML Logout request: " + stringWriter.toString());

  return Base64.encodeBase64String(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
}
 
Example #27
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testResponseInvalidVersion() throws Exception {
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress("http://apache.org");
    subjectConfirmationData.setInResponseTo("12345");
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient("http://recipient.apache.org");

    // Create a AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setNotBefore(new DateTime());
    conditions.setNotAfter(new DateTime().plusMinutes(5));

    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(Collections.singletonList("http://service.apache.org"));
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(conditions);

    Response response = createResponse(subjectConfirmationData, callbackHandler);
    response.setVersion(SAMLVersion.VERSION_10);

    // Validate the Response
    SAMLProtocolResponseValidator protocolValidator = new SAMLProtocolResponseValidator();

    try {
        protocolValidator.validateSamlResponse(response, null, null);
        fail("Expected failure on bad response");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example #28
Source File: DefaultAuthnRequestBuilder.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a SAML 2.0 Protocol AuthnRequest
 */
public AuthnRequest createAuthnRequest(
    Message message,
    String issuerId,
    String assertionConsumerServiceAddress
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameIDPolicy nameIDPolicy =
        SamlpRequestComponentBuilder.createNameIDPolicy(true, nameIDFormat, issuerId);

    AuthnContextClassRef authnCtxClassRef =
        SamlpRequestComponentBuilder.createAuthnCtxClassRef(
            "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
        );
    RequestedAuthnContext authnCtx =
        SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT,
            Collections.singletonList(authnCtxClassRef), null
        );

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createAuthnRequest(
            assertionConsumerServiceAddress,
            forceAuthn,
            isPassive,
            protocolBinding,
            SAMLVersion.VERSION_20,
            issuer,
            nameIDPolicy,
            authnCtx
    );

}
 
Example #29
Source File: SamlpRequestComponentBuilder.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static LogoutRequest createLogoutRequest(
    SAMLVersion version,
    Issuer issuer,
    String destination,
    String consent,
    Date notOnOrAfter,
    String reason,
    NameID nameID
) {
    if (logoutRequestBuilder == null) {
        logoutRequestBuilder = (SAMLObjectBuilder<LogoutRequest>)
            builderFactory.getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);
    }
    LogoutRequest logoutRequest = logoutRequestBuilder.buildObject();
    logoutRequest.setID("_" + UUID.randomUUID());
    logoutRequest.setVersion(version);
    logoutRequest.setIssueInstant(new DateTime());
    logoutRequest.setDestination(destination);
    logoutRequest.setConsent(consent);
    logoutRequest.setIssuer(issuer);
    if (notOnOrAfter != null) {
        logoutRequest.setNotOnOrAfter(new DateTime(notOnOrAfter.getTime()));
    }
    logoutRequest.setReason(reason);
    logoutRequest.setNameID(nameID);

    return logoutRequest;
}
 
Example #30
Source File: SamlpRequestComponentBuilder.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
//CHECKSTYLE:OFF
public static AuthnRequest createAuthnRequest(
    String serviceURL,
    boolean forceAuthn,
    boolean isPassive,
    String protocolBinding,
    SAMLVersion version,
    Issuer issuer,
    NameIDPolicy nameIDPolicy,
    RequestedAuthnContext requestedAuthnCtx
) {
//CHECKSTYLE:ON
    if (authnRequestBuilder == null) {
        authnRequestBuilder = (SAMLObjectBuilder<AuthnRequest>)
            builderFactory.getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    }
    AuthnRequest authnRequest = authnRequestBuilder.buildObject();
    authnRequest.setAssertionConsumerServiceURL(serviceURL);
    authnRequest.setForceAuthn(forceAuthn);
    authnRequest.setID("_" + UUID.randomUUID());
    authnRequest.setIsPassive(isPassive);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setProtocolBinding(protocolBinding);
    authnRequest.setVersion(version);

    authnRequest.setIssuer(issuer);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    authnRequest.setRequestedAuthnContext(requestedAuthnCtx);

    return authnRequest;
}