Search in sources :

Example 21 with TokenStore

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

the class STSInvoker method findCancelOrRenewToken.

private SecurityToken findCancelOrRenewToken(Exchange exchange, Element el) throws WSSecurityException {
    Element childElement = DOMUtils.getFirstElement(el);
    final String uri;
    if ("SecurityContextToken".equals(childElement.getLocalName())) {
        SecurityContextToken sct = new SecurityContextToken(childElement);
        uri = sct.getIdentifier();
    } else {
        SecurityTokenReference ref = new SecurityTokenReference(childElement, new BSPEnforcer());
        uri = ref.getReference().getURI();
    }
    TokenStore store = (TokenStore) exchange.getEndpoint().getEndpointInfo().getProperty(TokenStore.class.getName());
    return store.getToken(uri);
}
Also used : SecurityTokenReference(org.apache.wss4j.common.token.SecurityTokenReference) SecurityContextToken(org.apache.wss4j.dom.message.token.SecurityContextToken) Element(org.w3c.dom.Element) BSPEnforcer(org.apache.wss4j.common.bsp.BSPEnforcer) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore)

Example 22 with TokenStore

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

the class WSS4JInInterceptor method getCallback.

protected CallbackHandler getCallback(RequestData reqData) throws WSSecurityException, TokenStoreException {
    Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, (SoapMessage) reqData.getMsgContext());
    CallbackHandler cbHandler;
    try {
        cbHandler = SecurityUtils.getCallbackHandler(o);
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
    if (cbHandler == null) {
        try {
            cbHandler = getPasswordCallbackHandler(reqData);
        } catch (WSSecurityException sec) {
            Endpoint ep = ((SoapMessage) reqData.getMsgContext()).getExchange().getEndpoint();
            if (ep != null && ep.getEndpointInfo() != null) {
                TokenStore store = TokenStoreUtils.getTokenStore((SoapMessage) reqData.getMsgContext());
                return new TokenStoreCallbackHandler(null, store);
            }
            throw sec;
        }
    }
    // Defer to SecurityConstants.SIGNATURE_PASSWORD for decryption if no callback handler is defined
    if (cbHandler == null) {
        String signatureUser = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.SIGNATURE_USERNAME, (SoapMessage) reqData.getMsgContext());
        String password = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.SIGNATURE_PASSWORD, (SoapMessage) reqData.getMsgContext());
        if (!(StringUtils.isEmpty(signatureUser) || StringUtils.isEmpty(password))) {
            cbHandler = new CallbackHandler() {

                @Override
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback c : callbacks) {
                        WSPasswordCallback pwCallback = (WSPasswordCallback) c;
                        if (WSPasswordCallback.DECRYPT == pwCallback.getUsage() && signatureUser.equals(pwCallback.getIdentifier())) {
                            pwCallback.setPassword(password);
                        }
                    }
                }
            };
        }
    }
    Endpoint ep = ((SoapMessage) reqData.getMsgContext()).getExchange().getEndpoint();
    if (ep != null && ep.getEndpointInfo() != null) {
        TokenStore store = TokenStoreUtils.getTokenStore((SoapMessage) reqData.getMsgContext());
        return new TokenStoreCallbackHandler(cbHandler, store);
    }
    return cbHandler;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) SOAPException(javax.xml.soap.SOAPException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) XMLStreamException(javax.xml.stream.XMLStreamException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) TokenStoreException(org.apache.cxf.ws.security.tokenstore.TokenStoreException) IOException(java.io.IOException) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) Callback(javax.security.auth.callback.Callback) Endpoint(org.apache.cxf.endpoint.Endpoint) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore)

Example 23 with TokenStore

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

the class SecurityAssertionStore method getSecurityAssertion.

/**
 * Return the SecurityAssertion wrapper associated with the provided message
 *
 * @param message Message
 * @return SecurityAssertion
 */
public static SecurityAssertion getSecurityAssertion(Message message) {
    if (message != null) {
        TokenStore tokenStore = getTokenStore(message);
        Principal principal = null;
        SecurityContext context = message.get(SecurityContext.class);
        if (context != null) {
            principal = context.getUserPrincipal();
        }
        if (!(principal instanceof SAMLTokenPrincipal)) {
            // Try to find the SAMLTokenPrincipal if it exists
            List<?> wsResults = List.class.cast(message.get(WSHandlerConstants.RECV_RESULTS));
            if (wsResults != null) {
                for (Object wsResult : wsResults) {
                    if (wsResult instanceof WSHandlerResult) {
                        List<WSSecurityEngineResult> wsseResults = ((WSHandlerResult) wsResult).getResults();
                        for (WSSecurityEngineResult wsseResult : wsseResults) {
                            Object principalResult = wsseResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
                            if (principalResult instanceof SAMLTokenPrincipal) {
                                principal = (SAMLTokenPrincipal) principalResult;
                                break;
                            }
                        }
                    }
                }
            }
        }
        if (tokenStore != null && principal instanceof SAMLTokenPrincipal) {
            String id = ((SAMLTokenPrincipal) principal).getId();
            SamlAssertionWrapper samlAssertionWrapper = ((SAMLTokenPrincipal) principal).getToken();
            SecurityToken token = tokenStore.getToken(id);
            if (token == null) {
                if (samlAssertionWrapper.getSaml2().getIssueInstant() != null && samlAssertionWrapper.getSaml2().getConditions() != null && samlAssertionWrapper.getSaml2().getConditions().getNotOnOrAfter() != null) {
                    token = new SecurityToken(id, samlAssertionWrapper.getElement(), Instant.ofEpochMilli(samlAssertionWrapper.getSaml2().getIssueInstant().getMillis()), Instant.ofEpochMilli(samlAssertionWrapper.getSaml2().getConditions().getNotOnOrAfter().getMillis()));
                } else {
                    // we don't know how long this should last or when it was created, so just
                    // set it to 1 minute
                    // This shouldn't happen unless someone sets up a third party STS with weird
                    // settings.
                    Instant now = Instant.now();
                    token = new SecurityToken(id, samlAssertionWrapper.getElement(), now, now.plus(Duration.ofMinutes(1L)));
                }
                tokenStore.add(token);
            }
            return new SecurityAssertionSaml(samlAssertionWrapper.getElement());
        } else if (principal instanceof SecurityAssertionPrincipal) {
            return ((SecurityAssertionPrincipal) principal).getAssertion();
        }
    }
    return new SecurityAssertionSaml();
}
Also used : SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) SecurityAssertionPrincipal(ddf.security.assertion.SecurityAssertionPrincipal) Instant(java.time.Instant) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityContext(org.apache.cxf.security.SecurityContext) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore) SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) Principal(java.security.Principal) SecurityAssertionPrincipal(ddf.security.assertion.SecurityAssertionPrincipal) SecurityAssertionSaml(ddf.security.assertion.saml.impl.SecurityAssertionSaml)

Example 24 with TokenStore

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

the class ServerCachingTest method testServerSideSAMLTokenCaching.

@org.junit.Test
public void testServerSideSAMLTokenCaching() throws Exception {
    createBus(getClass().getResource("cxf-client.xml").toString());
    URL wsdl = ServerCachingTest.class.getResource("DoubleIt.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItTransportSAML1AlternativePort");
    DoubleItPortType port = service.getPort(portQName, DoubleItPortType.class);
    ((BindingProvider) port).getRequestContext().put("thread.local.request.context", "true");
    updateAddressPort(port, PORT);
    // Make an initial successful invocation
    doubleIt(port, 25);
    // Store the SAML Assertion that was obtained from the STS
    Client client = ClientProxy.getClient(port);
    Endpoint ep = client.getEndpoint();
    String id = (String) ep.get(SecurityConstants.TOKEN_ID);
    TokenStore store = (TokenStore) ep.getEndpointInfo().getProperty(TokenStore.class.getName());
    SecurityToken tok = store.getToken(id);
    assertNotNull(tok);
    Element storedToken = tok.getToken();
    // Get another security token by invoking on the STS directly and save it on the client port
    SecurityToken token = requestSecurityToken(SAML1_TOKEN_TYPE, PUBLIC_KEY_KEYTYPE, bus, DEFAULT_ADDRESS);
    assertNotNull(token);
    tok.setToken(token.getToken());
    // after the first invocation
    try {
        doubleIt(port, 30);
        fail("Failure expected as the STSClient on the server side is null");
    } catch (Exception ex) {
    // expected
    }
    // Try again using the original SAML token - this should work as it should be cached by the service
    tok.setToken(storedToken);
    doubleIt(port, 35);
    ((java.io.Closeable) port).close();
}
Also used : QName(javax.xml.namespace.QName) Element(org.w3c.dom.Element) Service(javax.xml.ws.Service) URL(java.net.URL) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Endpoint(org.apache.cxf.endpoint.Endpoint) DoubleItPortType(org.example.contract.doubleit.DoubleItPortType) Client(org.apache.cxf.endpoint.Client) STSClient(org.apache.cxf.ws.security.trust.STSClient) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore)

Example 25 with TokenStore

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

the class UsernameActAsCachingTest method testUsernameActAsCaching.

/**
 * Test caching the issued token
 */
@org.junit.Test
public void testUsernameActAsCaching() throws Exception {
    createBus(getClass().getResource("cxf-client.xml").toString());
    URL wsdl = UsernameActAsCachingTest.class.getResource("DoubleIt.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItAsymmetricSAML2BearerPort2");
    // 
    // Proxy no. 1
    // 
    DoubleItPortType port = service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(port, PORT);
    TokenTestUtils.updateSTSPort((BindingProvider) port, STSPORT2);
    TokenStore tokenStore = new MemoryTokenStore();
    ((BindingProvider) port).getRequestContext().put(TokenStore.class.getName(), tokenStore);
    // Make a successful invocation
    ((BindingProvider) port).getRequestContext().put(SecurityConstants.USERNAME, "alice");
    doubleIt(port, 25);
    // Change the STSClient so that it can no longer find the STS
    BindingProvider p = (BindingProvider) port;
    clearSTSClient(p);
    // This invocation should be successful as the token is cached
    doubleIt(port, 25);
    // 
    // Proxy no. 2
    // 
    DoubleItPortType port2 = service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(port2, PORT);
    TokenTestUtils.updateSTSPort((BindingProvider) port2, STSPORT2);
    // Change the STSClient so that it can no longer find the STS
    p = (BindingProvider) port2;
    clearSTSClient(p);
    // This should fail as the cache is not being used
    try {
        doubleIt(port2, 40);
        fail("Failure expected as the token is not stored in the cache");
    } catch (Exception ex) {
    // expected
    }
    // Set the cache correctly
    p.getRequestContext().put(TokenStore.class.getName(), tokenStore);
    // Make another invocation - this should succeed as the token is cached
    p.getRequestContext().put(SecurityConstants.USERNAME, "alice");
    doubleIt(port2, 40);
    // Reset the cache - this invocation should fail
    p.getRequestContext().put(TokenStore.class.getName(), new MemoryTokenStore());
    p.getRequestContext().put(SecurityConstants.TOKEN, new SecurityToken());
    try {
        doubleIt(port2, 40);
        fail("Failure expected as the cache is reset");
    } catch (Exception ex) {
    // expected
    }
    ((java.io.Closeable) port).close();
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) MemoryTokenStore(org.apache.cxf.ws.security.tokenstore.MemoryTokenStore) QName(javax.xml.namespace.QName) Service(javax.xml.ws.Service) DoubleItPortType(org.example.contract.doubleit.DoubleItPortType) BindingProvider(javax.xml.ws.BindingProvider) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore) MemoryTokenStore(org.apache.cxf.ws.security.tokenstore.MemoryTokenStore) URL(java.net.URL) BusException(org.apache.cxf.BusException) EndpointException(org.apache.cxf.endpoint.EndpointException)

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