Java Code Examples for org.apache.wss4j.dom.handler.RequestData#setCallbackHandler()

The following examples show how to use org.apache.wss4j.dom.handler.RequestData#setCallbackHandler() . 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: CallbackHandlerLoginHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public UserSubject createSubject(Client client, String user, String pass) {
    Document doc = DOMUtils.getEmptyDocument();
    UsernameToken token = new UsernameToken(false, doc,
                                            WSS4JConstants.PASSWORD_TEXT);
    token.setName(user);
    token.setPassword(pass);

    Credential credential = new Credential();
    credential.setUsernametoken(token);

    RequestData data = new RequestData();
    data.setMsgContext(PhaseInterceptorChain.getCurrentMessage());
    data.setCallbackHandler(callbackHandler);
    UsernameTokenValidator validator = new UsernameTokenValidator();

    try {
        credential = validator.validate(credential, data);

        UserSubject subject = new UserSubject();
        subject.setLogin(user);
        return subject;
    } catch (Exception ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example 2
Source File: SamlTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private List<WSSecurityEngineResult> processToken(Element tokenElement, final SoapMessage message)
    throws WSSecurityException {

    RequestData data = new CXFRequestData();
    Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message);
    try {
        data.setCallbackHandler(SecurityUtils.getCallbackHandler(o));
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
    data.setMsgContext(message);
    data.setWssConfig(WSSConfig.getNewInstance());

    data.setSigVerCrypto(getCrypto(SecurityConstants.SIGNATURE_CRYPTO,
                                 SecurityConstants.SIGNATURE_PROPERTIES, message));

    WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument());
    data.setWsDocInfo(wsDocInfo);

    SAMLTokenProcessor p = new SAMLTokenProcessor();
    return p.handleToken(tokenElement, data);
}
 
Example 3
Source File: BinarySecurityTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private List<WSSecurityEngineResult> processToken(Element tokenElement, final SoapMessage message)
    throws WSSecurityException {
    RequestData data = new CXFRequestData();
    Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message);
    try {
        data.setCallbackHandler(SecurityUtils.getCallbackHandler(o));
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
    }
    data.setMsgContext(message);
    data.setWssConfig(WSSConfig.getNewInstance());

    WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument());
    data.setWsDocInfo(wsDocInfo);

    BinarySecurityTokenProcessor p = new BinarySecurityTokenProcessor();
    return p.handleToken(tokenElement, data);
}
 
Example 4
Source File: STSUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private List<WSSecurityEngineResult> processToken(SecurityToken token) throws Exception {
    RequestData requestData = new RequestData();
    CallbackHandler callbackHandler = new CommonCallbackHandler();
    requestData.setCallbackHandler(callbackHandler);
    Crypto crypto = CryptoFactory.getInstance("clientKeystore.properties",
                                              this.getClass().getClassLoader());
    requestData.setSigVerCrypto(crypto);
    requestData.setWsDocInfo(new WSDocInfo(token.getToken().getOwnerDocument()));

    Processor processor = new SAMLTokenProcessor();
    return processor.handleToken(token.getToken(), requestData);
}
 
Example 5
Source File: BasicAuthFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    Message message = JAXRSUtils.getCurrentMessage();
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);

    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
        return;
    }

    try {
        UsernameToken token = convertPolicyToToken(policy);
        Credential credential = new Credential();
        credential.setUsernametoken(token);

        RequestData data = new RequestData();
        data.setMsgContext(message);
        data.setCallbackHandler(callbackHandler);
        UsernameTokenValidator validator = new UsernameTokenValidator();
        credential = validator.validate(credential, data);

        // Create a Principal/SecurityContext
        Principal p = null;
        if (credential != null && credential.getPrincipal() != null) {
            p = credential.getPrincipal();
        } else {
            p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
            ((WSUsernameTokenPrincipalImpl)p).setPassword(policy.getPassword());
        }
        message.put(SecurityContext.class, createSecurityContext(p));
    } catch (Exception ex) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
    }
}
 
Example 6
Source File: WSS4JBasicAuthValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void validate(Message message) throws WSSecurityException {

        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
            String name = null;
            if (policy != null) {
                name = policy.getUserName();
            }
            String errorMsg = "No user name and/or password is available, name: " + name;
            LOG.warning(errorMsg);
            throw new SecurityException(errorMsg);
        }

        UsernameToken token = convertPolicyToToken(policy);
        Credential credential = new Credential();
        credential.setUsernametoken(token);

        RequestData data = new RequestData();
        data.setMsgContext(message);
        data.setCallbackHandler(callbackHandler);
        credential = getValidator().validate(credential, data);

        // Create a Principal/SecurityContext
        SecurityContext sc = null;
        if (credential != null && credential.getPrincipal() != null) {
            sc = createSecurityContext(message, credential);
        } else {
            Principal p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
            ((WSUsernameTokenPrincipalImpl)p).setPassword(policy.getPassword());
            sc = createSecurityContext(p);
        }

        message.put(SecurityContext.class, sc);
    }
 
Example 7
Source File: AbstractSTSClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected byte[] decryptKey(Element child) throws TrustException, WSSecurityException, Base64DecodingException {
    String encryptionAlgorithm = X509Util.getEncAlgo(child);
    // For the SPNEGO case just return the decoded cipher value and decrypt it later
    if (encryptionAlgorithm != null && encryptionAlgorithm.endsWith("spnego#GSS_Wrap")) {
        // Get the CipherValue
        Element tmpE =
            XMLUtils.getDirectChildElement(child, "CipherData", WSS4JConstants.ENC_NS);
        byte[] cipherValue = null;
        if (tmpE != null) {
            tmpE =
                XMLUtils.getDirectChildElement(tmpE, "CipherValue", WSS4JConstants.ENC_NS);
            if (tmpE != null) {
                String content = DOMUtils.getContent(tmpE);
                cipherValue = org.apache.xml.security.utils.XMLUtils.decode(content);
            }
        }
        if (cipherValue == null) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, "noCipher");
        }
        return cipherValue;
    }
    try {
        EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
        WSDocInfo docInfo = new WSDocInfo(child.getOwnerDocument());
        RequestData data = new RequestData();
        data.setWssConfig(WSSConfig.getNewInstance());
        data.setDecCrypto(createCrypto(true));
        data.setCallbackHandler(createHandler());
        data.setWsDocInfo(docInfo);
        List<WSSecurityEngineResult> result = proc.handleToken(child, data);
        return
            (byte[])result.get(0).get(
                WSSecurityEngineResult.TAG_SECRET
            );
    } catch (IOException e) {
        throw new TrustException("ENCRYPTED_KEY_ERROR", e, LOG);
    }
}
 
Example 8
Source File: RequestParserUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test for fetching (and validating) a referenced BinarySecurityToken from a UseKey Element.
 */
@org.junit.Test
public void testUseKeyX509() throws Exception {
    Element secHeaderElement = (Element) parseStringToElement(SECURITY_HEADER_X509).getFirstChild();
    RequestSecurityTokenType request = createJaxbObject(USE_KEY_X509_REFERENCE);
    RequestParser parser = new RequestParser();

    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgContext = new WrappedMessageContext(msg);

    // Process the security header and store the results in the message context
    WSSecurityEngine securityEngine = new WSSecurityEngine();
    RequestData reqData = new RequestData();
    reqData.setSigVerCrypto(getCrypto());
    reqData.setCallbackHandler(new PasswordCallbackHandler());

    WSHandlerResult results =
        securityEngine.processSecurityHeader(secHeaderElement, reqData);
    List<WSHandlerResult> resultsList = new ArrayList<>();
    resultsList.add(results);
    msgContext.put(WSHandlerConstants.RECV_RESULTS, resultsList);

    RequestRequirements requestRequirements = parser.parseRequest(request, msgContext, null, null);

    assertNotNull(requestRequirements.getKeyRequirements().getReceivedCredential().getX509Cert());
}
 
Example 9
Source File: RequestParserUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test for fetching (and validating) a referenced SecurityContextToken.
 */
@org.junit.Test
public void testValidateSCT() throws Exception {
    Element secHeaderElement = (Element) parseStringToElement(SECURITY_HEADER).getFirstChild();
    RequestSecurityTokenType request = createJaxbObject(VALIDATE_SCT_REFERENCE);
    RequestParser parser = new RequestParser();

    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgContext = new WrappedMessageContext(msg);

    // Process the security header and store the results in the message context
    WSSecurityEngine securityEngine = new WSSecurityEngine();
    RequestData reqData = new RequestData();
    reqData.setCallbackHandler(new PasswordCallbackHandler());

    WSHandlerResult results =
        securityEngine.processSecurityHeader(secHeaderElement, reqData);
    List<WSHandlerResult> resultsList = new ArrayList<>();
    resultsList.add(results);
    msgContext.put(WSHandlerConstants.RECV_RESULTS, resultsList);

    RequestRequirements requestRequirements = parser.parseRequest(request, msgContext, null, null);

    SCTValidator sctValidator = new SCTValidator();
    assertTrue(sctValidator.canHandleToken(requestRequirements.getTokenRequirements().getValidateTarget()));
}
 
Example 10
Source File: RequestParserUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test for fetching (and cancelling) a referenced SecurityContextToken.
 */
@org.junit.Test
public void testCancelSCT() throws Exception {
    Element secHeaderElement = (Element) parseStringToElement(SECURITY_HEADER).getFirstChild();
    RequestSecurityTokenType request = createJaxbObject(CANCEL_SCT_REFERENCE);
    RequestParser parser = new RequestParser();

    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgContext = new WrappedMessageContext(msg);

    // Process the security header and store the results in the message context
    WSSecurityEngine securityEngine = new WSSecurityEngine();
    RequestData reqData = new RequestData();
    reqData.setCallbackHandler(new PasswordCallbackHandler());

    WSHandlerResult results =
        securityEngine.processSecurityHeader(secHeaderElement, reqData);
    List<WSHandlerResult> resultsList = new ArrayList<>();
    resultsList.add(results);
    msgContext.put(WSHandlerConstants.RECV_RESULTS, resultsList);

    RequestRequirements requestRequirements = parser.parseRequest(request, msgContext, null, null);

    SCTCanceller sctCanceller = new SCTCanceller();
    assertTrue(sctCanceller.canHandleToken(requestRequirements.getTokenRequirements().getCancelTarget()));
}
 
Example 11
Source File: SimpleBatchSTSClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected byte[] decryptKey(Element child) throws TrustException, WSSecurityException {
    String encryptionAlgorithm = X509Util.getEncAlgo(child);
    // For the SPNEGO case just return the decoded cipher value and decrypt it later
    if (encryptionAlgorithm != null && encryptionAlgorithm.endsWith("spnego#GSS_Wrap")) {
        // Get the CipherValue
        Element tmpE =
            XMLUtils.getDirectChildElement(child, "CipherData", WSS4JConstants.ENC_NS);
        byte[] cipherValue = null;
        if (tmpE != null) {
            tmpE =
                XMLUtils.getDirectChildElement(tmpE, "CipherValue", WSS4JConstants.ENC_NS);
            if (tmpE != null) {
                String content = DOMUtils.getContent(tmpE);
                cipherValue = Base64.getMimeDecoder().decode(content);
            }
        }
        if (cipherValue == null) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, "noCipher");
        }
        return cipherValue;
    }
    try {
        EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
        RequestData data = new RequestData();
        data.setWssConfig(WSSConfig.getNewInstance());
        data.setDecCrypto(createCrypto(true));
        data.setCallbackHandler(createHandler());

        WSDocInfo docInfo = new WSDocInfo(child.getOwnerDocument());
        data.setWsDocInfo(docInfo);

        List<WSSecurityEngineResult> result = proc.handleToken(child, data);
        return
            (byte[])result.get(0).get(
                WSSecurityEngineResult.TAG_SECRET
            );
    } catch (IOException e) {
        throw new TrustException("ENCRYPTED_KEY_ERROR", e, LOG);
    }
}
 
Example 12
Source File: CustomParameterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private List<WSSecurityEngineResult> processToken(Element assertionElement)
    throws Exception {
    RequestData requestData = new RequestData();
    requestData.setDisableBSPEnforcement(true);
    CallbackHandler callbackHandler = new org.apache.cxf.systest.sts.common.CommonCallbackHandler();
    requestData.setCallbackHandler(callbackHandler);
    Crypto crypto = CryptoFactory.getInstance("serviceKeystore.properties");
    requestData.setDecCrypto(crypto);
    requestData.setSigVerCrypto(crypto);
    requestData.setWsDocInfo(new WSDocInfo(assertionElement.getOwnerDocument()));

    Processor processor = new SAMLTokenProcessor();
    return processor.handleToken(assertionElement, requestData);
}
 
Example 13
Source File: STSRESTTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static List<WSSecurityEngineResult> processToken(Element assertionElement)
        throws Exception {
        RequestData requestData = new RequestData();
//        requestData.setDisableBSPEnforcement(true);
        requestData.setCallbackHandler(new org.apache.cxf.systest.sts.common.CommonCallbackHandler());
        requestData.setDecCrypto(serviceCrypto);
//        requestData.setSigVerCrypto(serviceCrypto);
        requestData.setWsDocInfo(new WSDocInfo(assertionElement.getOwnerDocument()));

        return new SAMLTokenProcessor().handleToken(assertionElement, requestData);
    }
 
Example 14
Source File: IssueUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private List<WSSecurityEngineResult> processToken(SecurityToken token) throws Exception {
    RequestData requestData = new RequestData();
    requestData.setDisableBSPEnforcement(true);
    CallbackHandler callbackHandler = new org.apache.cxf.systest.sts.common.CommonCallbackHandler();
    requestData.setCallbackHandler(callbackHandler);
    Crypto crypto = CryptoFactory.getInstance("serviceKeystore.properties");
    requestData.setDecCrypto(crypto);
    requestData.setSigVerCrypto(crypto);
    requestData.setWsDocInfo(new WSDocInfo(token.getToken().getOwnerDocument()));

    Processor processor = new SAMLTokenProcessor();
    return processor.handleToken(token.getToken(), requestData);
}
 
Example 15
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate the response signature
 */
private void validateResponseSignature(
    Signature signature,
    Document doc,
    Crypto sigCrypto,
    CallbackHandler callbackHandler
) throws WSSecurityException {
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    requestData.setWsDocInfo(new WSDocInfo(doc));

    SAMLKeyInfo samlKeyInfo = null;

    KeyInfo keyInfo = signature.getKeyInfo();
    if (keyInfo != null) {
        try {
            samlKeyInfo =
                SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
        } catch (WSSecurityException ex) {
            LOG.log(Level.FINE, "Error in getting KeyInfo from SAML Response: " + ex.getMessage(), ex);
            throw ex;
        }
    } else if (!keyInfoMustBeAvailable) {
        samlKeyInfo = createKeyInfoFromDefaultAlias(sigCrypto);
    }
    if (samlKeyInfo == null) {
        LOG.warning("No KeyInfo supplied in the SAMLResponse signature");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Validate Signature against profiles
    validateSignatureAgainstProfiles(signature, samlKeyInfo);

    // Now verify trust on the signature
    Credential trustCredential = new Credential();
    trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
    trustCredential.setCertificates(samlKeyInfo.getCerts());

    try {
        signatureValidator.validate(trustCredential, requestData);
    } catch (WSSecurityException e) {
        LOG.log(Level.FINE, "Error in validating signature on SAML Response: " + e.getMessage(), e);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}
 
Example 16
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate an internal Assertion
 */
private void validateAssertion(
    SamlAssertionWrapper assertion,
    Crypto sigCrypto,
    CallbackHandler callbackHandler,
    Document doc,
    boolean signedResponse
) throws WSSecurityException {
    Credential credential = new Credential();
    credential.setSamlAssertion(assertion);

    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);

    if (assertion.isSigned()) {
        if (assertion.getSaml1() != null) {
            assertion.getSaml1().getDOM().setIdAttributeNS(null, "AssertionID", true);
        } else {
            assertion.getSaml2().getDOM().setIdAttributeNS(null, "ID", true);
        }

        // Verify the signature
        try {
            Signature sig = assertion.getSignature();
            WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
            requestData.setWsDocInfo(docInfo);

            SAMLKeyInfo samlKeyInfo = null;

            KeyInfo keyInfo = sig.getKeyInfo();
            if (keyInfo != null) {
                samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
            } else if (!keyInfoMustBeAvailable) {
                samlKeyInfo = createKeyInfoFromDefaultAlias(sigCrypto);
            }

            if (samlKeyInfo == null) {
                LOG.warning("No KeyInfo supplied in the SAMLResponse assertion signature");
                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
            }

            assertion.verifySignature(samlKeyInfo);

            assertion.parseSubject(
                new WSSSAMLKeyInfoProcessor(requestData),
                requestData.getSigVerCrypto(),
                requestData.getCallbackHandler()
            );
        } catch (WSSecurityException e) {
            LOG.log(Level.FINE, "Assertion failed signature validation", e);
            throw e;
        }
    }

    // Validate the Assertion & verify trust in the signature
    try {
        SamlSSOAssertionValidator assertionValidator = new SamlSSOAssertionValidator(signedResponse);
        assertionValidator.validate(credential, requestData);
    } catch (WSSecurityException ex) {
        LOG.log(Level.FINE, "Assertion validation failed: " + ex.getMessage(), ex);
        throw ex;
    }
}
 
Example 17
Source File: FederationProcessorImpl.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Element decryptEncryptedRST(Element encryptedRST, FedizContext config) throws ProcessingException {

        KeyManager decryptionKeyManager = config.getDecryptionKey();
        if (decryptionKeyManager == null || decryptionKeyManager.getCrypto() == null) {
            LOG.debug("We must have a decryption Crypto instance configured to decrypt encrypted tokens");
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }
        String keyPassword = decryptionKeyManager.getKeyPassword();
        if (keyPassword == null) {
            LOG.debug("We must have a decryption key password to decrypt encrypted tokens");
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }

        EncryptedDataProcessor proc = new EncryptedDataProcessor();
        WSDocInfo docInfo = new WSDocInfo(encryptedRST.getOwnerDocument());
        RequestData data = new RequestData();
        data.setWsDocInfo(docInfo);

        // Disable WSS4J processing of the (decrypted) SAML Token
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        wssConfig.setProcessor(WSConstants.SAML_TOKEN, new NOOpProcessor());
        wssConfig.setProcessor(WSConstants.SAML2_TOKEN, new NOOpProcessor());
        data.setWssConfig(wssConfig);

        data.setDecCrypto(decryptionKeyManager.getCrypto());
        data.setCallbackHandler(new DecryptionCallbackHandler(keyPassword));
        try {
            List<WSSecurityEngineResult> result = proc.handleToken(encryptedRST, data);
            if (!result.isEmpty()) {
                @SuppressWarnings("unchecked")
                List<WSDataRef> dataRefs = (List<WSDataRef>)result.get(result.size() - 1)
                    .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
                if (dataRefs != null && !dataRefs.isEmpty()) {
                    return dataRefs.get(0).getProtectedElement();
                }
            }
        } catch (WSSecurityException e) {
            LOG.debug(e.getMessage(), e);
            throw new ProcessingException(TYPE.TOKEN_INVALID);
        }
        return null;
    }