Search in sources :

Example 61 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class ValidateJWTTransformationTest method testJWTToSAMLTransformationRealm.

@org.junit.Test
public void testJWTToSAMLTransformationRealm() throws Exception {
    TokenValidateOperation validateOperation = new TokenValidateOperation();
    // Add Token Validator
    JWTTokenValidator validator = new JWTTokenValidator();
    validator.setRealmCodec(new CustomJWTRealmCodec());
    validateOperation.setTokenValidators(Collections.singletonList(validator));
    // Add Token Provider
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    validateOperation.setTokenProviders(Collections.singletonList(samlTokenProvider));
    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    stsProperties.setRealmParser(new CustomRealmParser());
    stsProperties.setIdentityMapper(new CustomIdentityMapper());
    validateOperation.setStsProperties(stsProperties);
    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType = new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
    request.getAny().add(tokenType);
    // Create a JWTToken
    TokenProviderResponse providerResponse = createJWT();
    Element wrapper = createTokenWrapper((String) providerResponse.getToken());
    Document doc = wrapper.getOwnerDocument();
    wrapper = (Element) doc.appendChild(wrapper);
    ValidateTargetType validateTarget = new ValidateTargetType();
    validateTarget.setAny(wrapper);
    JAXBElement<ValidateTargetType> validateTargetType = new JAXBElement<ValidateTargetType>(QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget);
    request.getAny().add(validateTargetType);
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));
    msgCtx.put("url", "https");
    // realm "B"
    try {
        validateOperation.validate(request, principal, msgCtx);
    } catch (STSException ex) {
    // expected
    }
    samlTokenProvider.setRealmMap(createSamlRealms());
    RequestSecurityTokenResponseType response = validateOperation.validate(request, principal, msgCtx);
    assertTrue(validateResponse(response));
    // Test the generated token.
    Element assertion = null;
    for (Object tokenObject : response.getAny()) {
        if (tokenObject instanceof JAXBElement<?> && REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>) tokenObject).getName())) {
            RequestedSecurityTokenType rstType = (RequestedSecurityTokenType) ((JAXBElement<?>) tokenObject).getValue();
            assertion = (Element) rstType.getAny();
            break;
        }
    }
    assertNotNull(assertion);
    String tokenString = DOM2Writer.nodeToString(assertion);
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("ALICE"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
}
Also used : RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) StaticSTSProperties(org.apache.cxf.sts.StaticSTSProperties) RequestedSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) STSException(org.apache.cxf.ws.security.sts.provider.STSException) JAXBElement(javax.xml.bind.JAXBElement) Crypto(org.apache.wss4j.common.crypto.Crypto) SAMLTokenProvider(org.apache.cxf.sts.token.provider.SAMLTokenProvider) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) JWTTokenValidator(org.apache.cxf.sts.token.validator.jwt.JWTTokenValidator) WrappedMessageContext(org.apache.cxf.jaxws.context.WrappedMessageContext) SecurityContext(org.apache.cxf.security.SecurityContext) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) ValidateTargetType(org.apache.cxf.ws.security.sts.provider.model.ValidateTargetType) MessageImpl(org.apache.cxf.message.MessageImpl) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 62 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class ValidateTokenTransformationUnitTest method testUsernameTokenTransformationRealm.

/**
 * Test to successfully validate a UsernameToken (which was issued in realm "A") and
 * transform it into a SAML Assertion in Realm "B".
 */
@org.junit.Test
public void testUsernameTokenTransformationRealm() throws Exception {
    TokenValidateOperation validateOperation = new TokenValidateOperation();
    // Add Token Validator
    UsernameTokenValidator validator = new UsernameTokenValidator();
    validator.setUsernameTokenRealmCodec(new CustomUsernameTokenRealmCodec());
    validateOperation.setTokenValidators(Collections.singletonList(validator));
    // Add Token Provider
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    validateOperation.setTokenProviders(Collections.singletonList(samlTokenProvider));
    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    stsProperties.setRealmParser(new CustomRealmParser());
    stsProperties.setIdentityMapper(new CustomIdentityMapper());
    validateOperation.setStsProperties(stsProperties);
    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType = new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
    request.getAny().add(tokenType);
    // Create a UsernameToken
    JAXBElement<UsernameTokenType> usernameTokenType = createUsernameToken("alice", "clarinet");
    ValidateTargetType validateTarget = new ValidateTargetType();
    validateTarget.setAny(usernameTokenType);
    JAXBElement<ValidateTargetType> validateTargetType = new JAXBElement<ValidateTargetType>(QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget);
    request.getAny().add(validateTargetType);
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));
    msgCtx.put("url", "https");
    // realm "B"
    try {
        validateOperation.validate(request, principal, msgCtx);
    } catch (STSException ex) {
    // expected
    }
    samlTokenProvider.setRealmMap(createSamlRealms());
    RequestSecurityTokenResponseType response = validateOperation.validate(request, principal, msgCtx);
    assertTrue(validateResponse(response));
    // Test the generated token.
    Element assertion = null;
    for (Object tokenObject : response.getAny()) {
        if (tokenObject instanceof JAXBElement<?> && REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>) tokenObject).getName())) {
            RequestedSecurityTokenType rstType = (RequestedSecurityTokenType) ((JAXBElement<?>) tokenObject).getValue();
            assertion = (Element) rstType.getAny();
            break;
        }
    }
    assertNotNull(assertion);
    String tokenString = DOM2Writer.nodeToString(assertion);
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("ALICE"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
}
Also used : RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) StaticSTSProperties(org.apache.cxf.sts.StaticSTSProperties) PasswordString(org.apache.cxf.ws.security.sts.provider.model.secext.PasswordString) AttributedString(org.apache.cxf.ws.security.sts.provider.model.secext.AttributedString) RequestedSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) UsernameTokenValidator(org.apache.cxf.sts.token.validator.UsernameTokenValidator) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) STSException(org.apache.cxf.ws.security.sts.provider.STSException) JAXBElement(javax.xml.bind.JAXBElement) Crypto(org.apache.wss4j.common.crypto.Crypto) SAMLTokenProvider(org.apache.cxf.sts.token.provider.SAMLTokenProvider) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WrappedMessageContext(org.apache.cxf.jaxws.context.WrappedMessageContext) SecurityContext(org.apache.cxf.security.SecurityContext) ValidateTargetType(org.apache.cxf.ws.security.sts.provider.model.ValidateTargetType) MessageImpl(org.apache.cxf.message.MessageImpl) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 63 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class SAMLTokenRenewerLifetimeTest method testSaml2ExceededConfiguredMaxLifetime.

/**
 * Renew SAML 2 token with a with a lifetime
 * which exceeds configured maximum lifetime
 */
@org.junit.Test
public void testSaml2ExceededConfiguredMaxLifetime() throws Exception {
    // 30 minutes
    long maxLifetime = 30 * 60L;
    SAMLTokenRenewer samlTokenRenewer = new SAMLTokenRenewer();
    samlTokenRenewer.setVerifyProofOfPossession(false);
    samlTokenRenewer.setAllowRenewalAfterExpiry(true);
    DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider();
    conditionsProvider.setMaxLifetime(maxLifetime);
    conditionsProvider.setAcceptClientLifetime(true);
    samlTokenRenewer.setConditionsProvider(conditionsProvider);
    TokenRenewerParameters renewerParameters = createRenewerParameters();
    // Set expected lifetime to 35 minutes
    Instant creationTime = Instant.now();
    long requestedLifetime = 35 * 60L;
    Instant expirationTime = creationTime.plusSeconds(requestedLifetime);
    Lifetime lifetime = new Lifetime();
    lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    lifetime.setExpires(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    renewerParameters.getTokenRequirements().setLifetime(lifetime);
    CallbackHandler callbackHandler = new PasswordCallbackHandler();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    // Create token.
    Element samlToken = createSAMLAssertion(WSS4JConstants.WSS_SAML_TOKEN_TYPE, crypto, "mystskey", callbackHandler, 50, true, true);
    // Sleep to expire the token
    Thread.sleep(100);
    ReceivedToken renewTarget = new ReceivedToken(samlToken);
    renewTarget.setState(STATE.VALID);
    renewerParameters.getTokenRequirements().setRenewTarget(renewTarget);
    renewerParameters.setToken(renewTarget);
    assertTrue(samlTokenRenewer.canHandleToken(renewTarget));
    try {
        samlTokenRenewer.renewToken(renewerParameters);
        fail("Failure expected due to exceeded lifetime");
    } catch (STSException ex) {
    // expected
    }
}
Also used : Lifetime(org.apache.cxf.sts.request.Lifetime) CallbackHandler(javax.security.auth.callback.CallbackHandler) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) Crypto(org.apache.wss4j.common.crypto.Crypto) Instant(java.time.Instant) Element(org.w3c.dom.Element) DefaultConditionsProvider(org.apache.cxf.sts.token.provider.DefaultConditionsProvider) STSException(org.apache.cxf.ws.security.sts.provider.STSException) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken)

Example 64 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class SAMLTokenRenewerLifetimeTest method testSaml2ExceededDefaultMaxLifetime.

/**
 * Renew SAML 2 token with a with a lifetime
 * which exceeds default maximum lifetime
 */
@org.junit.Test
public void testSaml2ExceededDefaultMaxLifetime() throws Exception {
    SAMLTokenRenewer samlTokenRenewer = new SAMLTokenRenewer();
    samlTokenRenewer.setVerifyProofOfPossession(false);
    samlTokenRenewer.setAllowRenewalAfterExpiry(true);
    DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider();
    conditionsProvider.setAcceptClientLifetime(true);
    samlTokenRenewer.setConditionsProvider(conditionsProvider);
    TokenRenewerParameters renewerParameters = createRenewerParameters();
    // Set expected lifetime to Default max lifetime plus 1
    Instant creationTime = Instant.now();
    long requestedLifetime = DefaultConditionsProvider.DEFAULT_MAX_LIFETIME + 1;
    Instant expirationTime = creationTime.plusSeconds(requestedLifetime);
    Lifetime lifetime = new Lifetime();
    lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    lifetime.setExpires(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    renewerParameters.getTokenRequirements().setLifetime(lifetime);
    CallbackHandler callbackHandler = new PasswordCallbackHandler();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    // Create token.
    Element samlToken = createSAMLAssertion(WSS4JConstants.WSS_SAML_TOKEN_TYPE, crypto, "mystskey", callbackHandler, 50, true, true);
    // Sleep to expire the token
    Thread.sleep(100);
    ReceivedToken renewTarget = new ReceivedToken(samlToken);
    renewTarget.setState(STATE.VALID);
    renewerParameters.getTokenRequirements().setRenewTarget(renewTarget);
    renewerParameters.setToken(renewTarget);
    assertTrue(samlTokenRenewer.canHandleToken(renewTarget));
    try {
        samlTokenRenewer.renewToken(renewerParameters);
        fail("Failure expected due to exceeded lifetime");
    } catch (STSException ex) {
    // expected
    }
}
Also used : Lifetime(org.apache.cxf.sts.request.Lifetime) CallbackHandler(javax.security.auth.callback.CallbackHandler) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) Crypto(org.apache.wss4j.common.crypto.Crypto) Instant(java.time.Instant) Element(org.w3c.dom.Element) DefaultConditionsProvider(org.apache.cxf.sts.token.provider.DefaultConditionsProvider) STSException(org.apache.cxf.ws.security.sts.provider.STSException) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken)

Example 65 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class SAMLProviderKeyTypeTest method testDefaultSaml2SymmetricKeyAssertion.

/**
 * Create a default Saml2 SymmetricKey Assertion.
 */
@org.junit.Test
public void testDefaultSaml2SymmetricKeyAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters = createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.SYMMETRIC_KEY_KEYTYPE);
    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    Entropy entropy = new Entropy();
    BinarySecret binarySecret = new BinarySecret();
    binarySecret.setBinarySecretValue(WSSecurityUtil.generateNonce(256 / 8));
    entropy.setBinarySecret(binarySecret);
    providerParameters.getKeyRequirements().setEntropy(entropy);
    binarySecret.setBinarySecretType("bad-type");
    try {
        samlTokenProvider.createToken(providerParameters);
        fail("Failure expected on a bad type");
    } catch (STSException ex) {
    // expected as no type is provided
    }
    binarySecret.setBinarySecretType(STSConstants.NONCE_TYPE);
    try {
        samlTokenProvider.createToken(providerParameters);
        fail("Failure expected on no computed key algorithm");
    } catch (STSException ex) {
    // expected as no computed key algorithm is provided
    }
    providerParameters.getKeyRequirements().setComputedKeyAlgorithm(STSConstants.COMPUTED_KEY_PSHA1);
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);
    Element token = (Element) providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertFalse(tokenString.contains("AuthenticationStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_HOLDER_KEY));
    assertFalse(tokenString.contains(SAML2Constants.CONF_BEARER));
    // Test custom keySize
    SignatureProperties signatureProperties = providerParameters.getStsProperties().getSignatureProperties();
    signatureProperties.setMinimumKeySize(-8);
    providerParameters.getKeyRequirements().setKeySize(-8);
    try {
        samlTokenProvider.createToken(providerParameters);
        fail("Failure expected on a bad KeySize");
    } catch (STSException ex) {
    // expected on a bad KeySize
    }
    signatureProperties.setMinimumKeySize(128);
    providerParameters.getKeyRequirements().setKeySize(192);
    samlTokenProvider.createToken(providerParameters);
}
Also used : Element(org.w3c.dom.Element) SignatureProperties(org.apache.cxf.sts.SignatureProperties) STSException(org.apache.cxf.ws.security.sts.provider.STSException) Entropy(org.apache.cxf.sts.request.Entropy) BinarySecret(org.apache.cxf.sts.request.BinarySecret)

Aggregations

STSException (org.apache.cxf.ws.security.sts.provider.STSException)87 Element (org.w3c.dom.Element)33 Crypto (org.apache.wss4j.common.crypto.Crypto)31 JAXBElement (javax.xml.bind.JAXBElement)30 StaticSTSProperties (org.apache.cxf.sts.StaticSTSProperties)26 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)26 RequestSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType)26 WrappedMessageContext (org.apache.cxf.jaxws.context.WrappedMessageContext)25 MessageImpl (org.apache.cxf.message.MessageImpl)25 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)24 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)24 ServiceMBean (org.apache.cxf.sts.service.ServiceMBean)21 StaticService (org.apache.cxf.sts.service.StaticService)20 RequestSecurityTokenResponseCollectionType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseCollectionType)18 Document (org.w3c.dom.Document)18 Principal (java.security.Principal)14 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)14 EncryptionProperties (org.apache.cxf.sts.service.EncryptionProperties)14 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)13 SAMLTokenProvider (org.apache.cxf.sts.token.provider.SAMLTokenProvider)13