org.apache.wss4j.dom.handler.RequestData Java Examples

The following examples show how to use org.apache.wss4j.dom.handler.RequestData. 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: FedizSignatureTrustValidator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate whether the given certificate chain should be trusted.
 *
 * @param certificates the certificate chain that should be validated against the keystore
 * @param crypto A Crypto instance
 * @param data A RequestData instance
 * @param enableRevocation Whether revocation is enabled or not
 * @throws WSSecurityException if the certificate chain is not trusted
 */
protected void verifyTrustInCerts(
    X509Certificate[] certificates,
    Crypto crypto,
    RequestData data,
    boolean enableRevocation
) throws WSSecurityException {
    //
    // Use the validation method from the crypto to check whether the subjects'
    // certificate was really signed by the issuer stated in the certificate
    //
    crypto.verifyTrust(certificates, enableRevocation, null, null);
    String subjectString = certificates[0].getSubjectX500Principal().getName();
    LOG.debug(
        "Certificate path has been verified for certificate with subject {}", subjectString
    );
}
 
Example #2
Source File: CustomUTValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential cred = super.validate(credential, data);

    UsernameToken ut = credential.getUsernametoken();
    WSUsernameTokenPrincipalImpl principal =
        new WSUsernameTokenPrincipalImpl(ut.getName(), ut.isHashed());
    principal.setCreatedTime(ut.getCreated());
    principal.setNonce(principal.getNonce());
    principal.setPassword(ut.getPassword());
    principal.setPasswordType(ut.getPasswordType());

    Subject subject = new Subject();
    subject.getPrincipals().add(principal);
    if ("Alice".equals(ut.getName())) {
        subject.getPrincipals().add(new SimpleGroup("manager", ut.getName()));
    }
    subject.getPrincipals().add(new SimpleGroup("worker", ut.getName()));
    cred.setSubject(subject);

    return cred;
}
 
Example #3
Source File: CustomSaml2Validator.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();

    if (!"sts".equals(assertion.getIssuerString())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    Assertion saml2Assertion = assertion.getSaml2();
    if (saml2Assertion == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    List<AttributeStatement> attributeStatements = saml2Assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    return validatedCredential;
}
 
Example #4
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 #5
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 #6
Source File: OnBehalfOfValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();

    Assertion saml2Assertion = assertion.getSaml2();
    if (saml2Assertion == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    List<AttributeStatement> attributeStatements = saml2Assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    Subject subject = saml2Assertion.getSubject();
    NameID nameID = subject.getNameID();
    String subjectName = nameID.getValue();
    if ("alice".equals(subjectName) || "bob".equals(subjectName)) {
        return validatedCredential;
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example #7
Source File: DifferentRealmValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);

    SamlAssertionWrapper transformedToken = validatedCredential.getTransformedToken();
    if (transformedToken == null || transformedToken.getSaml2() == null
        || !"B-Issuer".equals(transformedToken.getIssuerString())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE);
    }

    Assertion assertion = transformedToken.getSaml2();
    if (!"B-Principal".equals(assertion.getSubject().getNameID().getValue())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE);
    }

    return validatedCredential;
}
 
Example #8
Source File: SCTTokenValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    // Sleep to make sure token gets replicated
    try {
        Thread.sleep(2 * 1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Credential validatedCredential = super.validate(credential, data);

    // Hack to verify the IssuedToken assertion, as this is not done by default in CXF for a
    // SecurityContextToken
    SoapMessage soapMessage = (SoapMessage)data.getMsgContext();
    AssertionInfoMap aim = soapMessage.get(AssertionInfoMap.class);
    Collection<AssertionInfo> ais = aim.get(SP12Constants.ISSUED_TOKEN);
    for (AssertionInfo ai : ais) {
        ai.setAsserted(true);
    }

    return validatedCredential;
}
 
Example #9
Source File: SCTTokenValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);

    SamlAssertionWrapper transformedToken = validatedCredential.getTransformedToken();
    if (transformedToken == null || transformedToken.getSaml2() == null
        || !"DoubleItSTSIssuer".equals(transformedToken.getIssuerString())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE);
    }

    transformedToken.parseSubject(
        new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(),
        data.getCallbackHandler()
    );
    SAMLKeyInfo keyInfo = transformedToken.getSubjectKeyInfo();
    byte[] secret = keyInfo.getSecret();
    validatedCredential.setSecretKey(secret);

    return validatedCredential;
}
 
Example #10
Source File: ClaimsValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();

    boolean valid = false;
    if (assertion.getSaml1() != null) {
        valid = handleSAML1Assertion(assertion.getSaml1());
    } else if (assertion.getSaml2() != null) {
        valid = handleSAML2Assertion(assertion.getSaml2());
    }

    if (valid) {
        return validatedCredential;
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example #11
Source File: STSSamlAssertionValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Try to verify trust on the assertion. If it fails, then set a boolean and return.
 * @param assertion The signed Assertion
 * @param data The RequestData context
 * @return A Credential instance
 * @throws WSSecurityException
 */
@Override
protected Credential verifySignedAssertion(
    SamlAssertionWrapper assertion,
    RequestData data
) throws WSSecurityException {
    try {
        Credential credential = super.verifySignedAssertion(assertion, data);
        trustVerificationSucceeded = true;
        return credential;
    } catch (WSSecurityException ex) {
        LOG.log(Level.WARNING, "Local trust verification of SAML assertion failed: " + ex.getMessage(),
                ex);
        trustVerificationSucceeded = false;
        return null;
    }
}
 
Example #12
Source File: PolicyBasedWSS4JInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Set a WSS4J AlgorithmSuite object on the RequestData context, to restrict the
 * algorithms that are allowed for encryption, signature, etc.
 */
protected void setAlgorithmSuites(SoapMessage message, RequestData data) throws WSSecurityException {
    AlgorithmSuiteTranslater translater = new AlgorithmSuiteTranslater();
    translater.translateAlgorithmSuites(message.get(AssertionInfoMap.class), data);

    // Allow for setting non-standard signature algorithms
    boolean asymmAlgSet = false;
    String asymSignatureAlgorithm =
        (String)message.getContextualProperty(SecurityConstants.ASYMMETRIC_SIGNATURE_ALGORITHM);
    if (asymSignatureAlgorithm != null && data.getAlgorithmSuite() != null) {
        data.getAlgorithmSuite().getSignatureMethods().clear();
        data.getAlgorithmSuite().getSignatureMethods().add(asymSignatureAlgorithm);
        asymmAlgSet = true;
    }

    String symSignatureAlgorithm =
        (String)message.getContextualProperty(SecurityConstants.SYMMETRIC_SIGNATURE_ALGORITHM);
    if (symSignatureAlgorithm != null && data.getAlgorithmSuite() != null) {
        if (!asymmAlgSet) {
            data.getAlgorithmSuite().getSignatureMethods().clear();
        }
        data.getAlgorithmSuite().getSignatureMethods().add(symSignatureAlgorithm);
    }
}
 
Example #13
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 #14
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected void verifyDigestPassword(
    org.apache.wss4j.dom.message.token.UsernameToken usernameToken,
    RequestData data
) throws WSSecurityException {
    if (!supportDigestPasswords) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    String user = usernameToken.getName();
    String password = usernameToken.getPassword();
    boolean isHashed = usernameToken.isHashed();
    String nonce = usernameToken.getNonce();
    String createdTime = usernameToken.getCreated();
    AbstractUsernameTokenAuthenticatingInterceptor.this.setSubject(
        user, password, isHashed, nonce, createdTime
    );
}
 
Example #15
Source File: WSS4JInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Do whatever is necessary to determine the action for the incoming message and
 * do whatever other setup work is necessary.
 *
 * @param msg
 * @param reqData
 */
protected void computeAction(SoapMessage msg, RequestData reqData) throws WSSecurityException {
    //
    // Try to get Crypto Provider from message context properties.
    // It gives a possibility to use external Crypto Provider
    //
    Crypto encCrypto =
        (Crypto)SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_CRYPTO, msg);
    if (encCrypto != null) {
        reqData.setDecCrypto(encCrypto);
    }
    Crypto sigCrypto =
        (Crypto)SecurityUtils.getSecurityPropertyValue(SecurityConstants.SIGNATURE_CRYPTO, msg);
    if (sigCrypto != null) {
        reqData.setSigVerCrypto(sigCrypto);
    }
}
 
Example #16
Source File: SamlAssertionValidator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
/**
 * Verify trust in the signature of a signed Assertion. This method is separate so that
 * the user can override if if they want.
 * @param assertion The signed Assertion
 * @param data The RequestData context
 * @return A Credential instance
 * @throws WSSecurityException
 */
@Override
protected Credential verifySignedAssertion(
    SamlAssertionWrapper assertion,
    RequestData data
) throws WSSecurityException {
    Credential credential = new Credential();
    SAMLKeyInfo samlKeyInfo = assertion.getSignatureKeyInfo();
    credential.setPublicKey(samlKeyInfo.getPublicKey());
    credential.setCertificates(samlKeyInfo.getCerts());

    FedizSignatureTrustValidator trustValidator = new FedizSignatureTrustValidator();
    trustValidator.setSignatureTrustType(signatureTrustType);
    trustValidator.setSubjectConstraints(subjectDNPatterns);

    return trustValidator.validate(credential, data);
}
 
Example #17
Source File: FedizSignatureTrustValidator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the credential argument. It must contain either some Certificates or a PublicKey.
 *
 * A Crypto and a CallbackHandler implementation is required to be set.
 *
 * @param credential the Credential to be validated
 * @param data the RequestData associated with the request
 * @throws WSSecurityException on a failed validation
 */
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null
        || ((credential.getCertificates() == null || credential.getCertificates().length == 0)
            && credential.getPublicKey() == null)) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }

    verifyTrust(credential, data);

    return credential;
}
 
Example #18
Source File: WSS4JInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void configureReplayCaches(RequestData reqData, List<Integer> actions, SoapMessage msg)
        throws WSSecurityException {
    if (isNonceCacheRequired(actions, msg)) {
        ReplayCache nonceCache =
            getReplayCache(
                msg, SecurityConstants.ENABLE_NONCE_CACHE, SecurityConstants.NONCE_CACHE_INSTANCE
            );
        reqData.setNonceReplayCache(nonceCache);
    }

    if (isTimestampCacheRequired(actions, msg)) {
        ReplayCache timestampCache =
            getReplayCache(
                msg, SecurityConstants.ENABLE_TIMESTAMP_CACHE, SecurityConstants.TIMESTAMP_CACHE_INSTANCE
            );
        reqData.setTimestampReplayCache(timestampCache);
    }

    if (isSamlCacheRequired(actions, msg)) {
        ReplayCache samlCache =
            getReplayCache(
                msg, SecurityConstants.ENABLE_SAML_ONE_TIME_USE_CACHE,
                SecurityConstants.SAML_ONE_TIME_USE_CACHE_INSTANCE
            );
        reqData.setSamlOneTimeUseReplayCache(samlCache);
    }
}
 
Example #19
Source File: IncomingSecurityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean handleInbound(SOAPMessageContext context) {
   SOAPMessage message = context.getMessage();
   WSSecurityEngine secEngine = new WSSecurityEngine();
   RequestData requestData = new RequestData();
   requestData.setWssConfig(this.config);

   try {
      SOAPHeader header = message.getSOAPHeader();
      if (header != null) {
         NodeList list = header.getElementsByTagNameNS(WSSE.getNamespaceURI(), WSSE.getLocalPart());
         if (list != null) {
            LOG.debug("Verify WS Security Header");

            for(int j = 0; j < list.getLength(); ++j) {
               List<WSSecurityEngineResult> results = secEngine.processSecurityHeader((Element)list.item(j), requestData);
               Iterator i$ = results.iterator();

               while(i$.hasNext()) {
                  WSSecurityEngineResult result = (WSSecurityEngineResult)i$.next();
                  if (!((Boolean)result.get("validated-token")).booleanValue()) {
                     StringBuffer sb = new StringBuffer();
                     sb.append("Unable to validate incoming soap message. Action [");
                     sb.append(result.get("action"));
                     sb.append("].");
                     throw new ProtocolException(sb.toString());
                  }
               }
            }
         }
      }

      return true;
   } catch (WSSecurityException var12) {
      throw new ProtocolException(var12);
   } catch (SOAPException var13) {
      throw new ProtocolException(var13);
   }
}
 
Example #20
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 #21
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void verifyUnknownPassword(
    org.apache.wss4j.dom.message.token.UsernameToken usernameToken,
    RequestData data
) throws WSSecurityException {
    AbstractUsernameTokenAuthenticatingInterceptor.this.setSubject(
        usernameToken.getName(), null, false, null, null
    );
}
 
Example #22
Source File: IncomingSecurityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean handleInbound(SOAPMessageContext context) {
   SOAPMessage message = context.getMessage();
   WSSecurityEngine secEngine = new WSSecurityEngine();
   RequestData requestData = new RequestData();
   requestData.setWssConfig(this.config);

   try {
      SOAPHeader header = message.getSOAPHeader();
      if (header != null) {
         NodeList list = header.getElementsByTagNameNS(WSSE.getNamespaceURI(), WSSE.getLocalPart());
         if (list != null) {
            LOG.debug("Verify WS Security Header");

            for(int j = 0; j < list.getLength(); ++j) {
               List<WSSecurityEngineResult> results = secEngine.processSecurityHeader((Element)list.item(j), requestData);
               Iterator i$ = results.iterator();

               while(i$.hasNext()) {
                  WSSecurityEngineResult result = (WSSecurityEngineResult)i$.next();
                  if (!(Boolean) result.get("validated-token")) {
                     StringBuffer sb = new StringBuffer();
                     sb.append("Unable to validate incoming soap message. Action [");
                     sb.append(result.get("action"));
                     sb.append("].");
                     throw new ProtocolException(sb.toString());
                  }
               }
            }
         }
      }

      return true;
   } catch (WSSecurityException var12) {
      throw new ProtocolException(var12);
   } catch (SOAPException var13) {
      throw new ProtocolException(var13);
   }
}
 
Example #23
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void verifyPlaintextPassword(
    org.apache.wss4j.dom.message.token.UsernameToken usernameToken,
    RequestData data
) throws WSSecurityException {
    AbstractUsernameTokenAuthenticatingInterceptor.this.setSubject(
        usernameToken.getName(), usernameToken.getPassword(), false, null, null
    );
}
 
Example #24
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void verifyCustomPassword(
    org.apache.wss4j.dom.message.token.UsernameToken usernameToken,
    RequestData data
) throws WSSecurityException {
    AbstractUsernameTokenAuthenticatingInterceptor.this.setSubject(
        usernameToken.getName(), usernameToken.getPassword(), false, null, null
    );
}
 
Example #25
Source File: CredentialsOutHandler.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public WSPasswordCallback getPassword(final String username,
		final int doAction, final String clsProp, final String refProp,
		final RequestData reqData) throws WSSecurityException {
	final UsernamePasswordCredentials c = (UsernamePasswordCredentials) this.credentialsSource
			.getCredentials(this.serviceConfiguration.getEndpointUrl().toString());

	return new WSPasswordCallback(c.getUsername(), c.getPassword(), null,
			WSPasswordCallback.USERNAME_TOKEN);
}
 
Example #26
Source File: AlgorithmSuiteTranslater.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void translateAlgorithmSuites(AssertionInfoMap aim, RequestData data) throws WSSecurityException {
    if (aim == null) {
        return;
    }

    List<org.apache.wss4j.policy.model.AlgorithmSuite> algorithmSuites =
        getAlgorithmSuites(getBindings(aim));
    if (!algorithmSuites.isEmpty()) {
        // Translate into WSS4J's AlgorithmSuite class
        AlgorithmSuite algorithmSuite = translateAlgorithmSuites(algorithmSuites);
        data.setAlgorithmSuite(algorithmSuite);
    }

    // Now look for an AlgorithmSuite for a SAML Assertion
    Collection<AssertionInfo> ais =
        PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.SAML_TOKEN);
    if (!ais.isEmpty()) {
        List<org.apache.wss4j.policy.model.AlgorithmSuite> samlAlgorithmSuites = new ArrayList<>();
        for (AssertionInfo ai : ais) {
            SamlToken samlToken = (SamlToken)ai.getAssertion();
            AbstractSecurityAssertion parentAssertion = samlToken.getParentAssertion();
            if (parentAssertion instanceof SupportingTokens
                && ((SupportingTokens)parentAssertion).getAlgorithmSuite() != null) {
                samlAlgorithmSuites.add(((SupportingTokens)parentAssertion).getAlgorithmSuite());
            }
        }

        if (!samlAlgorithmSuites.isEmpty()) {
            data.setSamlAlgorithmSuite(translateAlgorithmSuites(samlAlgorithmSuites));
        }
    }
}
 
Example #27
Source File: AbstractWSS4JInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected Crypto loadCryptoFromPropertiesFile(
    String propFilename,
    RequestData reqData
) throws WSSecurityException {
    Message message = (Message)reqData.getMsgContext();
    ClassLoader classLoader = this.getClassLoader(reqData.getMsgContext());
    PasswordEncryptor passwordEncryptor = getPasswordEncryptor(reqData);
    return
        WSS4JUtils.loadCryptoFromPropertiesFile(
            message, propFilename, classLoader, passwordEncryptor
        );
}
 
Example #28
Source File: CXFWSS4JInInterceptor.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
public Crypto loadSignatureCrypto(RequestData reqData) throws WSSecurityException {
	try {
           PasswordEncryptor passwordEncryptor = new PlainTextPasswordEcryptor();
           return new Merlin(getMerlinProperties(), ClassLoaderUtils.getDefaultClassLoader(), passwordEncryptor);
	} catch (Exception e) {
		throw new RiceRuntimeException(e);
	}
}
 
Example #29
Source File: IncomingSecurityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean handleInbound(SOAPMessageContext context) {
   SOAPMessage message = context.getMessage();
   WSSecurityEngine secEngine = new WSSecurityEngine();
   RequestData requestData = new RequestData();
   requestData.setWssConfig(this.config);

   try {
      SOAPHeader header = message.getSOAPHeader();
      if (header != null) {
         NodeList list = header.getElementsByTagNameNS(WSSE.getNamespaceURI(), WSSE.getLocalPart());
         if (list != null) {
            LOG.debug("Verify WS Security Header");

            for(int j = 0; j < list.getLength(); ++j) {
               List<WSSecurityEngineResult> results = secEngine.processSecurityHeader((Element)list.item(j), requestData);
               Iterator i$ = results.iterator();

               while(i$.hasNext()) {
                  WSSecurityEngineResult result = (WSSecurityEngineResult)i$.next();
                  if (!(Boolean)result.get("validated-token")) {
                     StringBuffer sb = new StringBuffer();
                     sb.append("Unable to validate incoming soap message. Action [");
                     sb.append(result.get("action"));
                     sb.append("].");
                     throw new ProtocolException(sb.toString());
                  }
               }
            }
         }
      }

      return true;
   } catch (WSSecurityException var12) {
      throw new ProtocolException(var12);
   } catch (SOAPException var13) {
      throw new ProtocolException(var13);
   }
}
 
Example #30
Source File: PolicyBasedWSS4JInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private PasswordEncryptor getPasswordEncryptor(SoapMessage soapMessage, RequestData requestData) {
    PasswordEncryptor passwordEncryptor =
        (PasswordEncryptor)soapMessage.getContextualProperty(
            SecurityConstants.PASSWORD_ENCRYPTOR_INSTANCE
        );
    if (passwordEncryptor != null) {
        return passwordEncryptor;
    }

    return super.getPasswordEncryptor(requestData);
}