org.apache.wss4j.common.saml.SamlAssertionWrapper Java Examples

The following examples show how to use org.apache.wss4j.common.saml.SamlAssertionWrapper. 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: UsernameTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private SecurityContext createSecurityContext(Message msg,
                                              SamlAssertionWrapper samlAssertion) {
    String roleAttributeName =
        (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.SAML_ROLE_ATTRIBUTENAME, msg);
    if (roleAttributeName == null || roleAttributeName.length() == 0) {
        roleAttributeName = WSS4JInInterceptor.SAML_ROLE_ATTRIBUTENAME_DEFAULT;
    }

    ClaimCollection claims =
        SAMLUtils.getClaims(samlAssertion);
    Set<Principal> roles =
        SAMLUtils.parseRolesFromClaims(claims, roleAttributeName, null);

    SAMLSecurityContext context =
        new SAMLSecurityContext(new SAMLTokenPrincipalImpl(samlAssertion), roles, claims);
    context.setIssuer(SAMLUtils.getIssuer(samlAssertion));
    context.setAssertionElement(SAMLUtils.getAssertionElement(samlAssertion));
    return context;
}
 
Example #2
Source File: SamlFormOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    Form form = getRequestForm(message);
    if (form == null) {
        return;
    }

    try {
        SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(message);

        Document doc = DOMUtils.newDocument();
        Element assertionElement = assertionWrapper.toDOM(doc);
        String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));

        updateForm(form, encodedToken);
    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example #3
Source File: SamlOAuthValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void validate(Message message, SamlAssertionWrapper wrapper) {
    validateSAMLVersion(wrapper);

    Conditions cs = wrapper.getSaml2().getConditions();
    validateAudience(message, cs);

    if (issuer != null) {
        String actualIssuer = getIssuer(wrapper);
        String expectedIssuer = OAuthConstants.CLIENT_ID.equals(issuer)
            ? wrapper.getSaml2().getSubject().getNameID().getValue() : issuer;
        if (actualIssuer == null || !actualIssuer.equals(expectedIssuer)) {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
    }
    if (!validateAuthenticationSubject(message, cs, wrapper.getSaml2().getSubject())) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
}
 
Example #4
Source File: OAuth2TestUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static String createToken(String audRestr, boolean saml2, boolean sign)
    throws WSSecurityException {
    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(sign);
    samlCallbackHandler.setAudience(audRestr);
    if (!saml2) {
        samlCallbackHandler.setSaml2(false);
        samlCallbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
    }

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);

    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
    if (samlCallback.isSignAssertion()) {
        samlAssertion.signAssertion(
            samlCallback.getIssuerKeyName(),
            samlCallback.getIssuerKeyPassword(),
            samlCallback.getIssuerCrypto(),
            samlCallback.isSendKeyValue(),
            samlCallback.getCanonicalizationAlgorithm(),
            samlCallback.getSignatureAlgorithm()
        );
    }

    return samlAssertion.assertionToString();
}
 
Example #5
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssuePublicKeySAML2Token() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .query("keyType", STSConstants.PUBLIC_KEY_KEYTYPE)
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getCerts());
}
 
Example #6
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssuePublicKeySAML2TokenShortKeyType() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .query("keyType", "PublicKey")
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getCerts());
}
 
Example #7
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssueBearerSAML1TokenShorKeyType() throws Exception {
    WebClient client = webClient()
        .path("saml1.1")
        .query("keyType", "Bearer")
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() == null && assertion.getSaml1() != null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(confirmMethod.contains("bearer"));
}
 
Example #8
Source File: AbstractSamlInHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void checkSubjectConfirmationData(Message message, SamlAssertionWrapper assertion) {
    String valSAMLSubjectConf =
        (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION,
                                                       message);
    boolean validateSAMLSubjectConf = true;
    if (valSAMLSubjectConf != null) {
        validateSAMLSubjectConf = Boolean.parseBoolean(valSAMLSubjectConf);
    }

    if (validateSAMLSubjectConf) {
        Certificate[] tlsCerts = getTLSCertificates(message);
        if (!checkHolderOfKey(message, assertion, tlsCerts)) {
            throwFault("Holder Of Key claim fails", null);
        }
        if (!checkSenderVouches(message, assertion, tlsCerts)) {
            throwFault("Sender vouchers claim fails", null);
        }
        if (!checkBearer(assertion, tlsCerts)) {
            throwFault("Bearer claim fails", null);
        }
    }
}
 
Example #9
Source File: SamlTokenPolicyValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Check the policy version against the received assertion
 */
private boolean checkVersion(
    AssertionInfoMap aim,
    SamlToken samlToken,
    SamlAssertionWrapper assertionWrapper
) {
    SamlTokenType samlTokenType = samlToken.getSamlTokenType();
    if ((samlTokenType == SamlTokenType.WssSamlV11Token10
        || samlTokenType == SamlTokenType.WssSamlV11Token11)
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_11) {
        return false;
    } else if (samlTokenType == SamlTokenType.WssSamlV20Token11
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_20) {
        return false;
    }

    if (samlTokenType != null) {
        PolicyUtils.assertPolicy(aim, new QName(samlToken.getVersion().getNamespace(), samlTokenType.name()));
    }
    return true;
}
 
Example #10
Source File: CustomParameterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Element validateSAMLSecurityTokenResponse(
     RequestSecurityTokenResponseType securityResponse, boolean saml2
) throws Exception {
    RequestedSecurityTokenType requestedSecurityToken = getRequestedSecurityToken(securityResponse);
    assertNotNull(requestedSecurityToken);

    // Process the token
    List<WSSecurityEngineResult> results =
        processToken((Element)requestedSecurityToken.getAny());

    assertTrue(results != null && results.size() == 1);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertNotNull(assertion);
    if (saml2) {
        assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
    } else {
        assertTrue(assertion.getSaml2() == null && assertion.getSaml1() != null);
    }
    assertTrue(assertion.isSigned());

    return (Element)results.get(0).get(WSSecurityEngineResult.TAG_TOKEN_ELEMENT);
}
 
Example #11
Source File: SAMLTokenRenewer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void signAssertion(
    SamlAssertionWrapper assertion,
    TokenRenewerParameters tokenParameters
) throws Exception {
    if (signToken) {
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        String realm = tokenParameters.getRealm();
        RealmProperties samlRealm = null;
        if (realm != null && realmMap.containsKey(realm)) {
            samlRealm = realmMap.get(realm);
        }

        signToken(assertion, samlRealm, stsProperties, tokenParameters.getKeyRequirements());
    } else {
        if (assertion.getSaml1().getSignature() != null) {
            assertion.getSaml1().setSignature(null);
        } else if (assertion.getSaml2().getSignature() != null) {
            assertion.getSaml2().setSignature(null);
        }
    }

}
 
Example #12
Source File: SAMLTokenValidatorOldTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    return DOM2Writer.nodeToString(doc);
}
 
Example #13
Source File: SAMLEncryptedResponseTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlResponseStr(AbstractSAMLCallbackHandler saml2CallbackHandler,
                                     String requestId,
                                     boolean signAssertion) throws Exception {
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_REQUEST_URL);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    saml2CallbackHandler.setConditions(cp);

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(TEST_CLIENT_ADDRESS);
    subjectConfirmationData.setInResponseTo(requestId);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(TEST_REQUEST_URL);
    saml2CallbackHandler.setSubjectConfirmationData(subjectConfirmationData);

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

    Element response = createEncryptedSamlResponse(assertion, "mystskey", signAssertion, requestId);
    return encodeResponse(response);
}
 
Example #14
Source File: SamlTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Check the policy version against the received assertion
 */
private boolean checkVersion(
    AssertionInfoMap aim,
    SamlToken samlToken,
    SamlAssertionWrapper assertionWrapper
) {
    SamlTokenType tokenType = samlToken.getSamlTokenType();
    if ((tokenType == SamlTokenType.WssSamlV11Token10
        || tokenType == SamlTokenType.WssSamlV11Token11)
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_11) {
        return false;
    } else if (tokenType == SamlTokenType.WssSamlV20Token11
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_20) {
        return false;
    }
    PolicyUtils.assertPolicy(aim, new QName(samlToken.getVersion().getNamespace(), tokenType.name()));
    return true;
}
 
Example #15
Source File: Saml2BearerGrantHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected UserSubject getGrantSubject(Message message, SamlAssertionWrapper wrapper) {
    SecurityContext sc = scProvider.getSecurityContext(message, wrapper);
    if (sc instanceof SAMLSecurityContext) {
        SAMLSecurityContext jaxrsSc = (SAMLSecurityContext)sc;
        Set<Principal> rolesP = jaxrsSc.getUserRoles();
        List<String> roles = new ArrayList<>();
        if (rolesP != null) {
            for (Principal p : rolesP) {
                roles.add(p.getName());
            }
        }
        return new SamlUserSubject(jaxrsSc.getUserPrincipal().getName(),
                                   roles,
                                   jaxrsSc.getClaims());
    }
    return new UserSubject(sc.getUserPrincipal().getName());

}
 
Example #16
Source File: SamlHeaderOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    try {
        SamlAssertionWrapper assertionWrapper = createAssertion(message);

        Document doc = DOMUtils.newDocument();
        Element assertionElement = assertionWrapper.toDOM(doc);
        String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));

        Map<String, List<String>> headers = getHeaders(message);

        StringBuilder builder = new StringBuilder();
        builder.append("SAML").append(' ').append(encodedToken);
        headers.put("Authorization",
            CastUtils.cast(Collections.singletonList(builder.toString()), String.class));

    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example #17
Source File: AbstractBindingBuilder.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Store a SAML Assertion as a SecurityToken
 */
protected void storeAssertionAsSecurityToken(SamlAssertionWrapper assertion) throws TokenStoreException {
    String id = findIDFromSamlToken(assertion.getElement());
    if (id == null) {
        return;
    }
    SecurityToken secToken = new SecurityToken(id);
    if (assertion.getSaml2() != null) {
        secToken.setTokenType(WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
    } else {
        secToken.setTokenType(WSS4JConstants.WSS_SAML_TOKEN_TYPE);
    }
    secToken.setToken(assertion.getElement());
    getTokenStore().add(secToken);
    message.put(SecurityConstants.TOKEN_ID, secToken.getId());
}
 
Example #18
Source File: SAMLTokenRenewer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void createNewConditions(SamlAssertionWrapper assertion, TokenRenewerParameters tokenParameters) {
    ConditionsBean conditions =
        conditionsProvider.getConditions(convertToProviderParameters(tokenParameters));

    if (assertion.getSaml1() != null) {
        org.opensaml.saml.saml1.core.Assertion saml1Assertion = assertion.getSaml1();
        saml1Assertion.setIssueInstant(new DateTime());

        org.opensaml.saml.saml1.core.Conditions saml1Conditions =
            SAML1ComponentBuilder.createSamlv1Conditions(conditions);

        saml1Assertion.setConditions(saml1Conditions);
    } else {
        org.opensaml.saml.saml2.core.Assertion saml2Assertion = assertion.getSaml2();
        saml2Assertion.setIssueInstant(new DateTime());

        org.opensaml.saml.saml2.core.Conditions saml2Conditions =
            SAML2ComponentBuilder.createConditions(conditions);

        saml2Assertion.setConditions(saml2Conditions);
    }
}
 
Example #19
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 #20
Source File: SamlResponseCreator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public String createSAMLResponse(RequestContext context, Idp idp, Element rpToken,
                                 String consumerURL, String requestId, String requestIssuer)
                                     throws ProcessingException {
    List<Element> samlTokens =
        DOMUtils.findAllElementsByTagNameNS(rpToken, WSConstants.SAML2_NS, "Assertion");
    if (samlTokens.isEmpty() || samlTokens.size() != 1) {
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }

    try {
        SamlAssertionWrapper wrapper = new SamlAssertionWrapper(samlTokens.get(0));
        if (wrapper.getSaml2() == null) {
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }

        String remoteAddr = WebUtils.getHttpServletRequest(context).getRemoteAddr();
        Assertion saml2Assertion =
            createSAML2Assertion(context, idp, wrapper, requestId, requestIssuer,
                                 remoteAddr, consumerURL);

        Element response = createResponse(idp, requestId, saml2Assertion);
        return encodeResponse(response);
    } catch (Exception ex) {
        LOG.warn("Error marshalling SAML Token: {}", ex.getMessage());
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }
}
 
Example #21
Source File: ActAsValidator.java    From cxf with Apache License 2.0 5 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");
    }

    // The technical user should be in the Subject
    Subject subject = saml2Assertion.getSubject();
    if (subject == null || subject.getNameID() == null
        || !subject.getNameID().getValue().contains("www.client.com")) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

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

    for (AttributeStatement statement : attributeStatements) {
        List<Attribute> attributes = statement.getAttributes();
        for (Attribute attribute : attributes) {
            if (!"CustomActAs".equals(attribute.getName()) && !"ActAs".equals(attribute.getName())) {
                continue;
            }
            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String text = attributeValueElement.getTextContent();
                if (text.contains("alice") || text.contains("bob")) {
                    return validatedCredential;
                }
            }
        }
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example #22
Source File: AsymmetricBindingHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
private String getSAMLToken() {

        List<WSHandlerResult> results = CastUtils.cast((List<?>)message.getExchange().getInMessage()
            .get(WSHandlerConstants.RECV_RESULTS));

        for (WSHandlerResult rResult : results) {
            List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults();

            for (WSSecurityEngineResult wser : wsSecEngineResults) {
                Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION);
                if (actInt.intValue() == WSConstants.ST_SIGNED
                    || actInt.intValue() == WSConstants.ST_UNSIGNED) {
                    Instant created = Instant.now();
                    Instant expires = created.plusSeconds(WSS4JUtils.getSecurityTokenLifetime(message) / 1000L);

                    String id = (String)wser.get(WSSecurityEngineResult.TAG_ID);
                    SecurityToken tempTok = new SecurityToken(id, created, expires);
                    tempTok.setSecret((byte[])wser.get(WSSecurityEngineResult.TAG_SECRET));
                    tempTok.setX509Certificate(
                        (X509Certificate)wser.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE), null
                    );

                    SamlAssertionWrapper samlAssertion =
                        (SamlAssertionWrapper)wser.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
                    if (samlAssertion.getSamlVersion() == SAMLVersion.VERSION_20) {
                        tempTok.setTokenType(WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
                    } else {
                        tempTok.setTokenType(WSS4JConstants.WSS_SAML_TOKEN_TYPE);
                    }

                    message.put(SecurityConstants.TOKEN, tempTok);

                    return id;
                }
            }
        }
        return null;
    }
 
Example #23
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Validate SAML 2 token which includes the role attribute with 2 values
 * Roles are encoded as a multiple saml attributes with the same name
 */
@org.junit.Test
public void validateSAML2TokenRoleMultiAttributes() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    callbackHandler.setMultiValueType(MultiValue.MULTI_ATTR);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    String rstr = createSamlToken(assertion, "mystskey", true);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    FedizResponse wfRes = wfProc.processRequest(wfReq, config);

    Assert.assertEquals("Principal name wrong", TEST_USER,
                        wfRes.getUsername());
    Assert.assertEquals("Issuer wrong", TEST_RSTR_ISSUER, wfRes.getIssuer());
    Assert.assertEquals("Two roles must be found", 2, wfRes.getRoles()
                        .size());
    assertClaims(wfRes.getClaims(), callbackHandler.getRoleAttributeName());
}
 
Example #24
Source File: CrossDomainValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);

    SamlAssertionWrapper token = validatedCredential.getSamlAssertion();
    if (token == null || token.getSaml2() == null
        || !"b-issuer".equals(token.getIssuerString())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE);
    }

    return validatedCredential;
}
 
Example #25
Source File: IssueUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the Bearer SAML1 case
 */
@org.junit.Test
public void testBearerSaml1() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");

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

    // Get a token
    SecurityToken token =
        requestSecurityToken(SAML1_TOKEN_TYPE, BEARER_KEYTYPE, bus, DEFAULT_ADDRESS);
    assertEquals(SAML1_TOKEN_TYPE, token.getTokenType());
    assertNotNull(token.getToken());

    // Process the token
    List<WSSecurityEngineResult> results = processToken(token);
    assertTrue(results != null && results.size() == 1);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertNotNull(assertion);
    assertTrue(assertion.getSaml1() != null && assertion.getSaml2() == null);
    assertTrue(assertion.isSigned());

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(confirmMethod != null && confirmMethod.contains("bearer"));

    bus.shutdown(true);
}
 
Example #26
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testTrustFailure() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    String rstr = createSamlToken(assertion, "mystskey", true);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("CLIENT_TRUST");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on non-trusted signing cert");
    } catch (ProcessingException ex) {
        // expected
    }
}
 
Example #27
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSAML1Claims() throws Exception {
    AttributeBean attributeBean = new AttributeBean();
    attributeBean.setSimpleName("role");
    attributeBean.setQualifiedName("http://schemas.xmlsoap.org/ws/2005/05/identity/claims");
    attributeBean.addAttributeValue("employee");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(false);
    samlCallbackHandler.setAttributes(Collections.singletonList(attributeBean));

    // Create the SAML Assertion via the CallbackHandler
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);

    Document doc = DOMUtils.newDocument();
    samlAssertion.toDOM(doc);

    ClaimCollection claims = SAMLUtils.getClaims(samlAssertion);
    assertEquals(claims.getDialect().toString(),
            "http://schemas.xmlsoap.org/ws/2005/05/identity");
    assertEquals(1, claims.size());

    // Check Claim values
    Claim claim = claims.get(0);
    assertEquals(claim.getClaimType(), SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    assertEquals(1, claim.getValues().size());
    assertTrue(claim.getValues().contains("employee"));

    // Check SAMLClaim values
    assertTrue(claim instanceof SAMLClaim);
    assertEquals("role", ((SAMLClaim)claim).getName());

    // Check roles
    Set<Principal> roles = SAMLUtils.parseRolesFromClaims(claims, "role", null);
    assertEquals(1, roles.size());
    Principal p = roles.iterator().next();
    assertEquals("employee", p.getName());

}
 
Example #28
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Validate SAML 1.1 token which includes the role attribute with 2 values
 * Roles are encoded as a multi-value saml attribute
 * Token embedded in RSTR 2005/02 - WS Federation 1.0
 */
@org.junit.Test
public void validateSAML1TokenWSFed10() throws Exception {
    SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler();
    callbackHandler.setStatement(SAML1CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    String rstr = createSamlToken(assertion, "mystskey", true, STSUtil.SAMPLE_RSTR_2005_02_MSG);
    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    FedizResponse wfRes = wfProc.processRequest(wfReq, config);

    Assert.assertEquals("Principal name wrong", TEST_USER,
                        wfRes.getUsername());
    Assert.assertEquals("Issuer wrong", TEST_RSTR_ISSUER, wfRes.getIssuer());
    Assert.assertEquals("Two roles must be found", 2, wfRes.getRoles()
                        .size());
    Assert.assertEquals("Audience wrong", TEST_AUDIENCE, wfRes.getAudience());
}
 
Example #29
Source File: AbstractSamlInHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Check the sender-vouches requirements against the received assertion. The SAML
 * Assertion and the request body must be signed by the same signature.
 */
protected boolean checkSenderVouches(
    Message message,
    SamlAssertionWrapper assertionWrapper,
    Certificate[] tlsCerts
) {
    //
    // If we have a 2-way TLS connection, then we don't have to check that the
    // assertion + body are signed

    // If no body is available (ex, with GET) then consider validating that
    // the base64-encoded token is signed by the same signature
    //
    if (tlsCerts != null && tlsCerts.length > 0) {
        return true;
    }
    List<String> confirmationMethods = assertionWrapper.getConfirmationMethods();
    for (String confirmationMethod : confirmationMethods) {
        if (OpenSAMLUtil.isMethodSenderVouches(confirmationMethod)) {

            Element signedElement = message.getContent(Element.class);
            Node assertionParent = assertionWrapper.getElement().getParentNode();

            // if we have a shared parent signed node then we can assume both
            // this SAML assertion and the main payload have been signed by the same
            // signature
            if (assertionParent != signedElement) {
                // if not then try to compare if the same cert/key was used to sign SAML token
                // and the payload
                SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSignatureKeyInfo();
                if (!compareCredentials(subjectKeyInfo, message, tlsCerts)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #30
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testInvalidStatusCode() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML1_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

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

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

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

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid SAML code");
    } catch (WSSecurityException ex) {
        // expected
    }
}