Java Code Examples for org.apache.wss4j.common.saml.bean.ConditionsBean#setTokenPeriodMinutes()

The following examples show how to use org.apache.wss4j.common.saml.bean.ConditionsBean#setTokenPeriodMinutes() . 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: JMSWSSecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsignedSAML2AudienceRestrictionTokenURI() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldService");
    QName portName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldPort");
    URL wsdl = getWSDLURL("/wsdl/jms_test.wsdl");
    HelloWorldService service = new HelloWorldService(wsdl, serviceName);

    String response = new String("Bonjour");
    HelloWorldPortType greeter = service.getPort(portName, HelloWorldPortType.class);

    SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
    callbackHandler.setSignAssertion(true);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);
    List<String> audiences = new ArrayList<>();
    audiences.add("jms:jndi:dynamicQueues/test.jmstransport.text");
    AudienceRestrictionBean audienceRestrictionBean = new AudienceRestrictionBean();
    audienceRestrictionBean.setAudienceURIs(audiences);
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestrictionBean));

    callbackHandler.setConditions(conditions);

    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);

    WSS4JOutInterceptor outInterceptor = new WSS4JOutInterceptor(outProperties);
    Client client = ClientProxy.getClient(greeter);
    client.getOutInterceptors().add(outInterceptor);

    String reply = greeter.sayHi();
    assertNotNull("no response received from service", reply);
    assertEquals(response, reply);

    ((java.io.Closeable)greeter).close();
}
 
Example 2
Source File: JMSWSSecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsignedSAML2AudienceRestrictionTokenBadURI() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldService");
    QName portName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldPort");
    URL wsdl = getWSDLURL("/wsdl/jms_test.wsdl");
    HelloWorldService service = new HelloWorldService(wsdl, serviceName);

    HelloWorldPortType greeter = service.getPort(portName, HelloWorldPortType.class);

    SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
    callbackHandler.setSignAssertion(true);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);
    List<String> audiences = new ArrayList<>();
    audiences.add("jms:jndi:dynamicQueues/test.jmstransport.text.bad");
    AudienceRestrictionBean audienceRestrictionBean = new AudienceRestrictionBean();
    audienceRestrictionBean.setAudienceURIs(audiences);
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestrictionBean));

    callbackHandler.setConditions(conditions);

    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);

    WSS4JOutInterceptor outInterceptor = new WSS4JOutInterceptor(outProperties);
    Client client = ClientProxy.getClient(greeter);
    client.getOutInterceptors().add(outInterceptor);

    try {
        greeter.sayHi();
        fail("Failure expected on a bad audience restriction");
    } catch (SOAPFaultException ex) {
        // expected
    }

    ((java.io.Closeable)greeter).close();
}
 
Example 3
Source File: JMSWSSecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsignedSAML2AudienceRestrictionTokenServiceName() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldService");
    QName portName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldPort");
    URL wsdl = getWSDLURL("/wsdl/jms_test.wsdl");
    HelloWorldService service = new HelloWorldService(wsdl, serviceName);

    String response = new String("Bonjour");
    HelloWorldPortType greeter = service.getPort(portName, HelloWorldPortType.class);

    SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
    callbackHandler.setSignAssertion(true);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);
    List<String> audiences = new ArrayList<>();
    audiences.add("{http://cxf.apache.org/hello_world_jms}HelloWorldService");
    AudienceRestrictionBean audienceRestrictionBean = new AudienceRestrictionBean();
    audienceRestrictionBean.setAudienceURIs(audiences);
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestrictionBean));

    callbackHandler.setConditions(conditions);

    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);

    WSS4JOutInterceptor outInterceptor = new WSS4JOutInterceptor(outProperties);
    Client client = ClientProxy.getClient(greeter);
    client.getOutInterceptors().add(outInterceptor);

    String reply = greeter.sayHi();
    assertNotNull("no response received from service", reply);
    assertEquals(response, reply);

    ((java.io.Closeable)greeter).close();
}
 
Example 4
Source File: JMSWSSecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsignedSAML2AudienceRestrictionTokenBadServiceName() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldService");
    QName portName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldPort");
    URL wsdl = getWSDLURL("/wsdl/jms_test.wsdl");
    HelloWorldService service = new HelloWorldService(wsdl, serviceName);

    HelloWorldPortType greeter = service.getPort(portName, HelloWorldPortType.class);

    SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
    callbackHandler.setSignAssertion(true);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);
    List<String> audiences = new ArrayList<>();
    audiences.add("{http://cxf.apache.org/hello_world_jms}BadHelloWorldService");
    AudienceRestrictionBean audienceRestrictionBean = new AudienceRestrictionBean();
    audienceRestrictionBean.setAudienceURIs(audiences);
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestrictionBean));

    callbackHandler.setConditions(conditions);

    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);

    WSS4JOutInterceptor outInterceptor = new WSS4JOutInterceptor(outProperties);
    Client client = ClientProxy.getClient(greeter);
    client.getOutInterceptors().add(outInterceptor);

    try {
        greeter.sayHi();
        fail("Failure expected on a bad audience restriction");
    } catch (SOAPFaultException ex) {
        // expected
    }

    ((java.io.Closeable)greeter).close();
}
 
Example 5
Source File: SamlTokenTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSaml2Replay() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = SamlTokenTest.class.getResource("client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = SamlTokenTest.class.getResource("DoubleItSaml.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItSaml2TransportPort");
    DoubleItPortType saml2Port =
            service.getPort(portQName, DoubleItPortType.class);
    String portNumber = PORT2;
    if (STAX_PORT.equals(test.getPort())) {
        portNumber = STAX_PORT2;
    }
    updateAddressPort(saml2Port, portNumber);

    // Create a SAML Token with no "OneTimeUse" Condition
    ((BindingProvider)saml2Port).getRequestContext().put(
        SecurityConstants.SAML_CALLBACK_HANDLER, new SamlCallbackHandler()
    );

    Client cxfClient = ClientProxy.getClient(saml2Port);
    SecurityHeaderCacheInterceptor cacheInterceptor =
        new SecurityHeaderCacheInterceptor();
    cxfClient.getOutInterceptors().add(cacheInterceptor);

    // Make two invocations...should succeed
    saml2Port.doubleIt(25);
    saml2Port.doubleIt(25);

    // Now create a SAML Token with a "OneTimeUse" Condition
    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);
    conditions.setOneTimeUse(true);

    SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
    callbackHandler.setConditions(conditions);

    ((BindingProvider)saml2Port).getRequestContext().put(
        SecurityConstants.SAML_CALLBACK_HANDLER, callbackHandler
    );

    cxfClient.getOutInterceptors().remove(cacheInterceptor);
    cacheInterceptor = new SecurityHeaderCacheInterceptor();
    cxfClient.getOutInterceptors().add(cacheInterceptor);

    // Make two invocations...should fail on the second one
    saml2Port.doubleIt(25);

    try {
        saml2Port.doubleIt(25);
        fail("Failure expected on a replayed SAML Assertion");
    } catch (javax.xml.ws.soap.SOAPFaultException ex) {
        assertTrue(ex.getMessage().contains(WSSecurityException.UNIFIED_SECURITY_ERR));
    }

    ((java.io.Closeable)saml2Port).close();
    bus.shutdown(true);
}
 
Example 6
Source File: DefaultConditionsProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Get a ConditionsBean object.
 */
@Override
public ConditionsBean getConditions(TokenProviderParameters providerParameters) {
    ConditionsBean conditions = new ConditionsBean();

    Lifetime tokenLifetime = providerParameters.getTokenRequirements().getLifetime();
    if (lifetime > 0) {
        if (acceptClientLifetime && tokenLifetime != null
                && (tokenLifetime.getCreated() != null || tokenLifetime.getExpires() != null)) {
            Instant creationTime = parsedInstantOrDefault(tokenLifetime.getCreated(), Instant.now());
            Instant expirationTime = parsedInstantOrDefault(tokenLifetime.getExpires(),
                    creationTime.plusSeconds(lifetime));

            // Check to see if the created time is in the future
            Instant validCreation = Instant.now();
            if (futureTimeToLive > 0) {
                validCreation = validCreation.plusSeconds(futureTimeToLive);
            }
            if (creationTime.isAfter(validCreation)) {
                LOG.fine("The Created Time is too far in the future");
                throw new STSException(
                    "The Created Time is too far in the future", STSException.INVALID_TIME
                );
            }

            long requestedLifetime = Duration.between(creationTime, expirationTime).getSeconds();
            if (requestedLifetime > getMaxLifetime()) {
                StringBuilder sb = new StringBuilder();
                sb.append("Requested lifetime [").append(requestedLifetime);
                sb.append(" sec] exceed configured maximum lifetime [").append(getMaxLifetime());
                sb.append(" sec]");
                LOG.warning(sb.toString());
                if (isFailLifetimeExceedance()) {
                    throw new STSException("Requested lifetime exceeds maximum lifetime",
                                           STSException.INVALID_TIME);
                }
                expirationTime = creationTime.plusSeconds(getMaxLifetime());
            }

            conditions.setNotAfter(expirationTime);
            conditions.setNotBefore(creationTime);

        } else {
            conditions.setTokenPeriodSeconds(lifetime);
        }
    } else {
        conditions.setTokenPeriodMinutes(5);
    }

    List<AudienceRestrictionBean> audienceRestrictions = createAudienceRestrictions(providerParameters);
    if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
        conditions.setAudienceRestrictions(audienceRestrictions);
    }

    return conditions;
}
 
Example 7
Source File: SamlSso.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
protected Element createResponse(String requestID, String racs, String requestIssuer) throws Exception {
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );
    String issuer = messageContext.getUriInfo().getAbsolutePath().toString();
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestID, issuer, status);

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setIssuer(issuer);
    String user = messageContext.getSecurityContext().getUserPrincipal().getName();
    callbackHandler.setSubjectName(user);

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(messageContext.getHttpServletRequest().getRemoteAddr());
    subjectConfirmationData.setInResponseTo(requestID);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(racs);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    // Audience Restriction
    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);

    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(Collections.singletonList(requestIssuer));
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(conditions);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    Crypto issuerCrypto = CryptoFactory.getInstance("stsKeystoreB.properties");
    assertion.signAssertion("realmb", "realmb", issuerCrypto, false);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);

    return policyElement;
}
 
Example 8
Source File: SamlResponseCreator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Assertion createSAML2Assertion(RequestContext context, Idp idp, SamlAssertionWrapper receivedToken,
                                       String requestID, String requestIssuer,
                                       String remoteAddr, String racs) throws Exception {
    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    String issuer = isUseRealmForIssuer() ? idp.getRealm() : idp.getIdpUrl().toString();
    callbackHandler.setIssuer(issuer);
    callbackHandler.setSubject(receivedToken.getSaml2().getSubject());

    // Test Subject against received Subject (if applicable)
    SAMLAuthnRequest authnRequest =
        (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
    if (authnRequest.getSubjectNameId() != null && receivedToken.getSaml2().getSubject().getNameID() != null) {
        NameID issuedNameId = receivedToken.getSaml2().getSubject().getNameID();
        if (!authnRequest.getSubjectNameId().equals(issuedNameId.getValue())) {
            LOG.debug("Received NameID value of {} does not match issued value {}",
                      authnRequest.getSubjectNameId(), issuedNameId.getValue());
            throw new ProcessingException(ProcessingException.TYPE.INVALID_REQUEST);
        }
    }

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(remoteAddr);
    subjectConfirmationData.setInResponseTo(requestID);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(racs);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    // Audience Restriction
    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);

    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(Collections.singletonList(requestIssuer));
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(conditions);

    // Attributes
    callbackHandler.setAttributeStatements(receivedToken.getSaml2().getAttributeStatements());

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    Crypto issuerCrypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
    assertion.signAssertion(issuerCrypto.getDefaultX509Identifier(), idp.getCertificatePassword(),
                            issuerCrypto, false);

    return assertion.getSaml2();
}