Search in sources :

Example 11 with TokenStore

use of org.apache.cxf.ws.security.tokenstore.TokenStore in project cxf by apache.

the class CachingTest method testSymmetricSharedCache.

// Here we manually create a cache and share it for both proxies
@org.junit.Test
public void testSymmetricSharedCache() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = CachingTest.class.getResource("client.xml");
    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);
    URL wsdl = CachingTest.class.getResource("DoubleItCache.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItCacheSymmetricPort");
    // First invocation
    DoubleItPortType port = service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(port, test.getPort());
    // Create shared cache
    String cacheKey = SecurityConstants.TOKEN_STORE_CACHE_INSTANCE + '-' + Math.abs(new Random().nextInt());
    TokenStore tokenStore = new EHCacheTokenStore(cacheKey, bus, ClassLoaderUtils.getResource("cxf-ehcache.xml", this.getClass()));
    Client client = ClientProxy.getClient(port);
    client.getEndpoint().getEndpointInfo().setProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, tokenStore);
    if (test.isStreaming()) {
        SecurityTestUtil.enableStreaming(port);
    }
    assertEquals(50, port.doubleIt(25));
    // We expect two tokens as the identifier + SHA-1 are cached
    assertEquals(2, tokenStore.getTokenIdentifiers().size());
    // Second invocation
    DoubleItPortType port2 = service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(port2, test.getPort());
    client = ClientProxy.getClient(port2);
    client.getEndpoint().getEndpointInfo().setProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, tokenStore);
    if (test.isStreaming()) {
        SecurityTestUtil.enableStreaming(port2);
    }
    port2.doubleIt(35);
    client = ClientProxy.getClient(port2);
    tokenStore = (TokenStore) client.getEndpoint().getEndpointInfo().getProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE);
    assertNotNull(tokenStore);
    // We expect four tokens as the identifier + SHA-1 are cached
    assertEquals(4, tokenStore.getTokenIdentifiers().size());
    ((java.io.Closeable) port).close();
    ((java.io.Closeable) port2).close();
    bus.shutdown(true);
}
Also used : Bus(org.apache.cxf.Bus) QName(javax.xml.namespace.QName) Service(javax.xml.ws.Service) EHCacheTokenStore(org.apache.cxf.ws.security.tokenstore.EHCacheTokenStore) URL(java.net.URL) SpringBusFactory(org.apache.cxf.bus.spring.SpringBusFactory) Random(java.util.Random) DoubleItPortType(org.example.contract.doubleit.DoubleItPortType) Client(org.apache.cxf.endpoint.Client) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore) EHCacheTokenStore(org.apache.cxf.ws.security.tokenstore.EHCacheTokenStore)

Example 12 with TokenStore

use of org.apache.cxf.ws.security.tokenstore.TokenStore in project cxf by apache.

the class AbstractPolicySecurityTest method runOutInterceptorAndValidateSamlTokenAttached.

protected void runOutInterceptorAndValidateSamlTokenAttached(String policyDoc) throws Exception {
    // create the request message
    final Document document = this.readDocument("wsse-request-clean.xml");
    final Element outPolicyElement = this.readDocument(policyDoc).getDocumentElement();
    final Policy policy = this.policyBuilder.getPolicy(outPolicyElement);
    AssertionInfoMap aim = new AssertionInfoMap(policy);
    SoapMessage msg = this.getOutSoapMessageForDom(document, aim);
    // add an "issued" assertion into the message exchange
    Element issuedAssertion = this.readDocument("example-sts-issued-saml-assertion.xml").getDocumentElement();
    Properties cryptoProps = new Properties();
    URL url = ClassLoader.getSystemResource("outsecurity.properties");
    cryptoProps.load(url.openStream());
    Crypto crypto = CryptoFactory.getInstance(cryptoProps);
    // Sign the "issued" assertion
    SamlAssertionWrapper assertionWrapper = new SamlAssertionWrapper(issuedAssertion);
    assertionWrapper.signAssertion("myalias", "myAliasPassword", crypto, false);
    Document doc = DOMUtils.newDocument();
    issuedAssertion = OpenSAMLUtil.toDom(assertionWrapper.getSaml1(), doc);
    String assertionId = issuedAssertion.getAttributeNodeNS(null, "AssertionID").getNodeValue();
    SecurityToken issuedToken = new SecurityToken(assertionId, issuedAssertion, null);
    String alias = cryptoProps.getProperty("org.apache.ws.security.crypto.merlin.keystore.alias");
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(alias);
    issuedToken.setX509Certificate(crypto.getX509Certificates(cryptoType)[0], crypto);
    msg.getExchange().getEndpoint().put(SecurityConstants.TOKEN_ID, issuedToken.getId());
    msg.getExchange().put(SecurityConstants.TOKEN_ID, issuedToken.getId());
    TokenStore tokenStore = new MemoryTokenStore();
    msg.getExchange().getEndpoint().getEndpointInfo().setProperty(TokenStore.class.getName(), tokenStore);
    tokenStore.add(issuedToken);
    // fire the interceptor and verify results
    final Document signedDoc = this.runOutInterceptorAndValidate(msg, policy, aim, null, null);
    this.runInInterceptorAndValidate(signedDoc, policy, Collections.singletonList(SP12Constants.ISSUED_TOKEN), null, Collections.singletonList(CoverageType.SIGNED));
}
Also used : Policy(org.apache.neethi.Policy) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) CryptoType(org.apache.wss4j.common.crypto.CryptoType) Document(org.w3c.dom.Document) Properties(java.util.Properties) URL(java.net.URL) AssertionInfoMap(org.apache.cxf.ws.policy.AssertionInfoMap) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) MemoryTokenStore(org.apache.cxf.ws.security.tokenstore.MemoryTokenStore) Crypto(org.apache.wss4j.common.crypto.Crypto) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore) MemoryTokenStore(org.apache.cxf.ws.security.tokenstore.MemoryTokenStore)

Example 13 with TokenStore

use of org.apache.cxf.ws.security.tokenstore.TokenStore in project cxf by apache.

the class SAMLTokenRenewer method renewToken.

/**
 * Renew a token given a TokenRenewerParameters
 */
public TokenRenewerResponse renewToken(TokenRenewerParameters tokenParameters) {
    TokenRenewerResponse response = new TokenRenewerResponse();
    ReceivedToken tokenToRenew = tokenParameters.getToken();
    if (tokenToRenew == null || tokenToRenew.getToken() == null || (tokenToRenew.getState() != STATE.EXPIRED && tokenToRenew.getState() != STATE.VALID)) {
        LOG.log(Level.WARNING, "The token to renew is null or invalid");
        throw new STSException("The token to renew is null or invalid", STSException.INVALID_REQUEST);
    }
    TokenStore tokenStore = tokenParameters.getTokenStore();
    if (tokenStore == null) {
        LOG.log(Level.FINE, "A cache must be configured to use the SAMLTokenRenewer");
        throw new STSException("Can't renew SAML assertion", STSException.REQUEST_FAILED);
    }
    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper((Element) tokenToRenew.getToken());
        byte[] oldSignature = assertion.getSignatureValue();
        int hash = Arrays.hashCode(oldSignature);
        SecurityToken cachedToken = tokenStore.getToken(Integer.toString(hash));
        if (cachedToken == null) {
            LOG.log(Level.FINE, "The token to be renewed must be stored in the cache");
            throw new STSException("Can't renew SAML assertion", STSException.REQUEST_FAILED);
        }
        // Validate the Assertion
        validateAssertion(assertion, tokenToRenew, cachedToken, tokenParameters);
        SamlAssertionWrapper renewedAssertion = new SamlAssertionWrapper(assertion.getSamlObject());
        String oldId = createNewId(renewedAssertion);
        // Remove the previous token (now expired) from the cache
        tokenStore.remove(oldId);
        tokenStore.remove(Integer.toString(hash));
        // Create new Conditions & sign the Assertion
        createNewConditions(renewedAssertion, tokenParameters);
        signAssertion(renewedAssertion, tokenParameters);
        Document doc = DOMUtils.createDocument();
        Element token = renewedAssertion.toDOM(doc);
        if (renewedAssertion.getSaml1() != null) {
            token.setIdAttributeNS(null, "AssertionID", true);
        } else {
            token.setIdAttributeNS(null, "ID", true);
        }
        doc.appendChild(token);
        // Cache the token
        storeTokenInCache(tokenStore, renewedAssertion, tokenParameters.getPrincipal(), tokenParameters);
        response.setToken(token);
        response.setTokenId(renewedAssertion.getId());
        final DateTime validFrom;
        final DateTime validTill;
        if (renewedAssertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
            validFrom = renewedAssertion.getSaml2().getConditions().getNotBefore();
            validTill = renewedAssertion.getSaml2().getConditions().getNotOnOrAfter();
        } else {
            validFrom = renewedAssertion.getSaml1().getConditions().getNotBefore();
            validTill = renewedAssertion.getSaml1().getConditions().getNotOnOrAfter();
        }
        response.setCreated(validFrom.toDate().toInstant());
        response.setExpires(validTill.toDate().toInstant());
        LOG.fine("SAML Token successfully renewed");
        return response;
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "", ex);
        throw new STSException("Can't renew SAML assertion", ex, STSException.REQUEST_FAILED);
    }
}
Also used : Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Document(org.w3c.dom.Document) DateTime(org.joda.time.DateTime) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) STSException(org.apache.cxf.ws.security.sts.provider.STSException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore)

Example 14 with TokenStore

use of org.apache.cxf.ws.security.tokenstore.TokenStore in project ddf by codice.

the class UPBSTValidatorTest method testValidateGoodTokenCache.

@Test
public void testValidateGoodTokenCache() {
    UPBSTValidator upbstValidator = getUpbstValidator(new XmlParser(), meanValidator);
    upbstValidator.addRealm(null);
    TokenValidatorParameters tokenParameters = new TokenValidatorParameters();
    tokenParameters.setTokenStore(new TokenStore() {

        @Override
        public void add(SecurityToken token) {
        }

        @Override
        public void add(String identifier, SecurityToken token) {
        }

        @Override
        public void remove(String identifier) {
        }

        @Override
        public Collection<String> getTokenIdentifiers() {
            return null;
        }

        @Override
        public SecurityToken getToken(String identifier) {
            SecurityToken securityToken = new SecurityToken();
            securityToken.setTokenHash(584149325);
            return securityToken;
        }
    });
    ReceivedToken validateTarget = new ReceivedToken(upbstToken);
    tokenParameters.setToken(validateTarget);
    tokenParameters.setStsProperties(stsPropertiesMBean);
    TokenValidatorResponse response = upbstValidator.validateToken(tokenParameters);
    Assert.assertEquals(ReceivedToken.STATE.VALID, response.getToken().getState());
    verify(failedLoginDelayer, never()).delay(anyString());
}
Also used : TokenValidatorParameters(org.apache.cxf.sts.token.validator.TokenValidatorParameters) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) XmlParser(org.codice.ddf.parser.xml.XmlParser) Collection(java.util.Collection) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) Matchers.anyString(org.mockito.Matchers.anyString) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore) Test(org.junit.Test)

Example 15 with TokenStore

use of org.apache.cxf.ws.security.tokenstore.TokenStore in project ddf by codice.

the class UPBSTValidatorTest method testNoFailedDelayer.

@Test(expected = IllegalStateException.class)
public void testNoFailedDelayer() {
    UPBSTValidator upbstValidator = new UPBSTValidator(new XmlParser(), null) {

        public void addRealm(ServiceReference<JaasRealm> serviceReference) {
            validators.put("realm", meanValidator);
        }
    };
    upbstValidator.addRealm(null);
    TokenValidatorParameters tokenParameters = new TokenValidatorParameters();
    tokenParameters.setTokenStore(new TokenStore() {

        @Override
        public void add(SecurityToken token) {
        }

        @Override
        public void add(String identifier, SecurityToken token) {
        }

        @Override
        public void remove(String identifier) {
        }

        @Override
        public Collection<String> getTokenIdentifiers() {
            return null;
        }

        @Override
        public SecurityToken getToken(String identifier) {
            SecurityToken securityToken = new SecurityToken();
            securityToken.setTokenHash(584149325);
            return securityToken;
        }
    });
    ReceivedToken validateTarget = new ReceivedToken(upbstToken);
    tokenParameters.setToken(validateTarget);
    tokenParameters.setStsProperties(stsPropertiesMBean);
    upbstValidator.validateToken(tokenParameters);
}
Also used : TokenValidatorParameters(org.apache.cxf.sts.token.validator.TokenValidatorParameters) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) XmlParser(org.codice.ddf.parser.xml.XmlParser) Collection(java.util.Collection) Matchers.anyString(org.mockito.Matchers.anyString) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Aggregations

TokenStore (org.apache.cxf.ws.security.tokenstore.TokenStore)26 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)17 URL (java.net.URL)9 QName (javax.xml.namespace.QName)8 Service (javax.xml.ws.Service)8 DoubleItPortType (org.example.contract.doubleit.DoubleItPortType)8 Client (org.apache.cxf.endpoint.Client)7 Element (org.w3c.dom.Element)6 Bus (org.apache.cxf.Bus)5 Endpoint (org.apache.cxf.endpoint.Endpoint)5 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)5 Collection (java.util.Collection)4 SpringBusFactory (org.apache.cxf.bus.spring.SpringBusFactory)4 TokenValidatorParameters (org.apache.cxf.sts.token.validator.TokenValidatorParameters)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)4 Test (org.junit.Test)4 Matchers.anyString (org.mockito.Matchers.anyString)4 SoapMessage (org.apache.cxf.binding.soap.SoapMessage)3 MemoryTokenStore (org.apache.cxf.ws.security.tokenstore.MemoryTokenStore)3