org.apache.wss4j.common.crypto.Crypto Java Examples
The following examples show how to use
org.apache.wss4j.common.crypto.Crypto.
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: IssueOnbehalfofUnitTest.java From cxf with Apache License 2.0 | 6 votes |
private Element createSAMLAssertion( String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler, Map<String, RealmProperties> realms, String keyType ) throws WSSecurityException { SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider(); samlTokenProvider.setRealmMap(realms); TokenProviderParameters providerParameters = createProviderParameters( tokenType, keyType, crypto, signatureUsername, callbackHandler ); if (realms != null) { providerParameters.setRealm("A"); } TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters); assertNotNull(providerResponse); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); return (Element)providerResponse.getToken(); }
Example #2
Source File: IssueSamlUnitTest.java From cxf with Apache License 2.0 | 6 votes |
private UseKeyType createUseKey(Crypto crypto, String alias) throws Exception { CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(alias); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); Document doc = DOMUtils.getEmptyDocument(); Element x509Data = doc.createElementNS(WSS4JConstants.SIG_NS, "ds:X509Data"); x509Data.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:ds", WSS4JConstants.SIG_NS); Element x509Cert = doc.createElementNS(WSS4JConstants.SIG_NS, "ds:X509Certificate"); Text certText = doc.createTextNode(Base64.getMimeEncoder().encodeToString(certs[0].getEncoded())); x509Cert.appendChild(certText); x509Data.appendChild(x509Cert); UseKeyType useKey = new UseKeyType(); useKey.setAny(x509Data); return useKey; }
Example #3
Source File: AbstractBindingBuilder.java From cxf with Apache License 2.0 | 6 votes |
private X509Certificate getEncryptCert(Crypto crypto, String encrUser) throws WSSecurityException { // Check for prepared encryption certificate X509Certificate encrCert = (X509Certificate)SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_CERT, message); if (encrCert != null) { return encrCert; } CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(encrUser); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); if (certs != null && certs.length > 0) { return certs[0]; } return null; }
Example #4
Source File: IssueJWTOnbehalfofUnitTest.java From cxf with Apache License 2.0 | 6 votes |
private Element createSAMLAssertion( String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler, Map<String, RealmProperties> realms, String keyType ) throws WSSecurityException { SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider(); samlTokenProvider.setRealmMap(realms); TokenProviderParameters providerParameters = createProviderParameters( tokenType, keyType, crypto, signatureUsername, callbackHandler ); if (realms != null) { providerParameters.setRealm("A"); } TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters); assertNotNull(providerResponse); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); return (Element)providerResponse.getToken(); }
Example #5
Source File: AbstractSTSClient.java From cxf with Apache License 2.0 | 6 votes |
protected X509Certificate getCert(Crypto crypto) throws Exception { if (crypto == null) { throw new Fault("No Crypto token properties are available to retrieve a certificate", LOG); } String alias = (String)getProperty(SecurityConstants.STS_TOKEN_USERNAME); if (alias == null) { alias = crypto.getDefaultX509Identifier(); } if (alias == null) { throw new Fault("No alias specified for retrieving PublicKey", LOG); } CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(alias); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); if (certs == null || certs.length == 0) { throw new Fault("Could not get X509Certificate for alias " + alias, LOG); } return certs[0]; }
Example #6
Source File: SimpleBatchSTSClient.java From cxf with Apache License 2.0 | 6 votes |
protected X509Certificate getCert(Crypto crypto) throws Exception { String alias = (String)getProperty(SecurityConstants.STS_TOKEN_USERNAME); if (alias == null) { alias = crypto.getDefaultX509Identifier(); } if (alias == null) { throw new Fault("No alias specified for retrieving PublicKey", LOG); } CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(alias); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); if (certs == null || certs.length == 0) { throw new Fault("Could not get X509Certificate for alias " + alias, LOG); } return certs[0]; }
Example #7
Source File: SAMLDelegationTest.java From cxf with Apache License 2.0 | 6 votes |
private Element createSAMLAssertion( String tokenType, String keyType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler, String user, String issuer ) throws WSSecurityException { SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider(); TokenProviderParameters providerParameters = createProviderParameters( tokenType, keyType, crypto, signatureUsername, callbackHandler, user, issuer ); TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters); assertNotNull(providerResponse); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); return (Element)providerResponse.getToken(); }
Example #8
Source File: WSSecHeaderGeneratorWss4jImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public void sign(AbstractWsSecurityHandler.SignedParts... parts) throws TechnicalConnectorException { try { if (this.cred instanceof SAMLHolderOfKeyToken && StringUtils.isNotEmpty(this.assertionId)) { this.sign.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1"); this.sign.setKeyIdentifierType(12); this.sign.setCustomTokenValueType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID"); this.sign.setCustomTokenId(this.assertionId); } else { this.sign.setKeyIdentifierType(1); } Crypto crypto = new WSSecurityCrypto(this.cred.getPrivateKey(), this.cred.getCertificate()); this.sign.prepare(this.soapPart, crypto, this.wsSecHeader); if (!(this.cred instanceof SAMLHolderOfKeyToken) || !StringUtils.isNotEmpty(this.assertionId)) { this.sign.appendBSTElementToHeader(this.wsSecHeader); } List<Reference> referenceList = this.sign.addReferencesToSign(this.generateReferencesToSign(parts), this.wsSecHeader); if (!referenceList.isEmpty()) { this.sign.computeSignature(referenceList, false, (Element)null); } } catch (WSSecurityException var4) { throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.HANDLER_ERROR, new Object[]{"unable to insert security header.", var4}); } }
Example #9
Source File: WSSecHeaderGeneratorWss4jImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public void sign(AbstractWsSecurityHandler.SignedParts... parts) throws TechnicalConnectorException { try { if (StringUtils.isNotEmpty(this.assertionId)) { this.sign.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#rsa-sha1"); this.sign.setKeyIdentifierType(12); this.sign.setCustomTokenValueType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID"); this.sign.setCustomTokenId(this.assertionId); } else { this.sign.setKeyIdentifierType(1); } Crypto crypto = new WSSecurityCrypto(this.cred.getPrivateKey(), this.cred.getCertificate()); this.sign.prepare(this.soapPart, crypto, this.wsSecHeader); if (StringUtils.isEmpty(this.assertionId)) { this.sign.appendBSTElementToHeader(this.wsSecHeader); } List<Reference> referenceList = this.sign.addReferencesToSign(this.generateReferencesToSign(parts), this.wsSecHeader); if (!referenceList.isEmpty()) { this.sign.computeSignature(referenceList, false, (Element)null); } } catch (WSSecurityException var4) { throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.HANDLER_ERROR, new Object[]{"unable to insert security header.", var4}); } }
Example #10
Source File: IssueUnitTest.java From cxf with Apache License 2.0 | 5 votes |
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 #11
Source File: JAXRSOAuth2Test.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testSAML2BearerAuthenticationDirect() throws Exception { String address = "https://localhost:" + port + "/oauth2-auth/token"; WebClient wc = createWebClient(address); Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES); SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password"); SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true); samlCallbackHandler.setIssuer("alice"); String audienceURI = "https://localhost:" + port + "/oauth2-auth/token"; samlCallbackHandler.setAudience(audienceURI); SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler, signInfo); Document doc = DOMUtils.newDocument(); Element assertionElement = assertionWrapper.toDOM(doc); String assertion = DOM2Writer.nodeToString(assertionElement); String encodedAssertion = Base64UrlUtility.encode(assertion); Map<String, String> extraParams = new HashMap<>(); extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER); extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion); ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams); assertNotNull(at.getTokenKey()); }
Example #12
Source File: IssueUnitTest.java From cxf with Apache License 2.0 | 5 votes |
private TokenProviderParameters createProviderParameters( String tokenType, String keyType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler, String username, String issuer ) throws WSSecurityException { TokenProviderParameters parameters = new TokenProviderParameters(); TokenRequirements tokenRequirements = new TokenRequirements(); tokenRequirements.setTokenType(tokenType); parameters.setTokenRequirements(tokenRequirements); KeyRequirements keyRequirements = new KeyRequirements(); keyRequirements.setKeyType(keyType); parameters.setKeyRequirements(keyRequirements); parameters.setPrincipal(new CustomTokenPrincipal(username)); // Mock up message context MessageImpl msg = new MessageImpl(); WrappedMessageContext msgCtx = new WrappedMessageContext(msg); parameters.setMessageContext(msgCtx); parameters.setAppliesToAddress( "https://localhost:" + STSPORT + "/SecurityTokenService/b-issuer/Transport"); // Add STSProperties object StaticSTSProperties stsProperties = new StaticSTSProperties(); stsProperties.setSignatureCrypto(crypto); stsProperties.setSignatureUsername(signatureUsername); stsProperties.setCallbackHandler(callbackHandler); stsProperties.setIssuer(issuer); parameters.setStsProperties(stsProperties); parameters.setEncryptionProperties(new EncryptionProperties()); return parameters; }
Example #13
Source File: JWTTokenValidatorRealmTest.java From cxf with Apache License 2.0 | 5 votes |
private TokenValidatorParameters createValidatorParameters() throws WSSecurityException { TokenValidatorParameters parameters = new TokenValidatorParameters(); TokenRequirements tokenRequirements = new TokenRequirements(); tokenRequirements.setTokenType(STSConstants.STATUS); parameters.setTokenRequirements(tokenRequirements); KeyRequirements keyRequirements = new KeyRequirements(); parameters.setKeyRequirements(keyRequirements); parameters.setPrincipal(new CustomTokenPrincipal("alice")); // Mock up message context MessageImpl msg = new MessageImpl(); WrappedMessageContext msgCtx = new WrappedMessageContext(msg); parameters.setMessageContext(msgCtx); // Add STSProperties object StaticSTSProperties 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"); parameters.setStsProperties(stsProperties); parameters.setTokenStore(tokenStore); return parameters; }
Example #14
Source File: SAMLTokenValidatorRealmTest.java From cxf with Apache License 2.0 | 5 votes |
private TokenValidatorParameters createValidatorParameters() throws WSSecurityException { TokenValidatorParameters parameters = new TokenValidatorParameters(); TokenRequirements tokenRequirements = new TokenRequirements(); tokenRequirements.setTokenType(STSConstants.STATUS); parameters.setTokenRequirements(tokenRequirements); KeyRequirements keyRequirements = new KeyRequirements(); parameters.setKeyRequirements(keyRequirements); parameters.setPrincipal(new CustomTokenPrincipal("alice")); // Mock up message context MessageImpl msg = new MessageImpl(); WrappedMessageContext msgCtx = new WrappedMessageContext(msg); parameters.setMessageContext(msgCtx); // Add STSProperties object StaticSTSProperties 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-2"); parameters.setStsProperties(stsProperties); return parameters; }
Example #15
Source File: SAMLTokenValidatorTest.java From cxf with Apache License 2.0 | 5 votes |
private Element createSAMLAssertion( String subjectName, String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler ) throws WSSecurityException { TokenProvider samlTokenProvider = new SAMLTokenProvider(); TokenProviderParameters providerParameters = createProviderParameters( subjectName, tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername, callbackHandler ); TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters); assertNotNull(providerResponse); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); return (Element)providerResponse.getToken(); }
Example #16
Source File: SAMLProviderKeyTypeTest.java From cxf with Apache License 2.0 | 5 votes |
/** * Create a default Saml1 PublicKey Assertion. */ @org.junit.Test public void testDefaultSaml1PublicKeyAssertion() throws Exception { TokenProvider samlTokenProvider = new SAMLTokenProvider(); TokenProviderParameters providerParameters = createProviderParameters(WSS4JConstants.SAML_NS, STSConstants.PUBLIC_KEY_KEYTYPE); assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.SAML_NS)); try { samlTokenProvider.createToken(providerParameters); fail("Failure expected on no certificate"); } catch (STSException ex) { // expected as no certificate is provided } // Now get a certificate and set it on the key requirements of the provider parameter Crypto crypto = providerParameters.getStsProperties().getEncryptionCrypto(); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("myclientkey"); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); ReceivedCredential receivedCredential = new ReceivedCredential(); receivedCredential.setX509Cert(certs[0]); providerParameters.getKeyRequirements().setReceivedCredential(receivedCredential); 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(SAML1Constants.CONF_HOLDER_KEY)); assertFalse(tokenString.contains(SAML1Constants.CONF_BEARER)); }
Example #17
Source File: SCTValidatorTest.java From cxf with Apache License 2.0 | 5 votes |
private TokenValidatorParameters createValidatorParameters() throws WSSecurityException { TokenValidatorParameters parameters = new TokenValidatorParameters(); TokenRequirements tokenRequirements = new TokenRequirements(); tokenRequirements.setTokenType(STSConstants.STATUS); parameters.setTokenRequirements(tokenRequirements); KeyRequirements keyRequirements = new KeyRequirements(); parameters.setKeyRequirements(keyRequirements); parameters.setTokenStore(tokenStore); parameters.setPrincipal(new CustomTokenPrincipal("alice")); // Mock up message context MessageImpl msg = new MessageImpl(); WrappedMessageContext msgCtx = new WrappedMessageContext(msg); parameters.setMessageContext(msgCtx); // Add STSProperties object StaticSTSProperties 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"); parameters.setStsProperties(stsProperties); return parameters; }
Example #18
Source File: ValidateSamlUnitTest.java From cxf with Apache License 2.0 | 5 votes |
private Element createSAMLAssertion( String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler ) throws WSSecurityException { TokenProvider samlTokenProvider = new SAMLTokenProvider(); TokenProviderParameters providerParameters = createProviderParameters( tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername, callbackHandler ); TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters); assertNotNull(providerResponse); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); return (Element)providerResponse.getToken(); }
Example #19
Source File: TrustedIdpSAMLProtocolHandler.java From cxf-fediz with Apache License 2.0 | 5 votes |
/** * Validate the received SAML Response as per the protocol */ private void validateSamlResponseProtocol( org.opensaml.saml.saml2.core.Response samlResponse, Crypto crypto, TrustedIdp trustedIdp ) { try { SAMLProtocolResponseValidator protocolValidator = new SAMLProtocolResponseValidator(); protocolValidator.setKeyInfoMustBeAvailable( isBooleanPropertyConfigured(trustedIdp, REQUIRE_KEYINFO, true)); protocolValidator.validateSamlResponse(samlResponse, crypto, null); } catch (WSSecurityException ex) { LOG.debug(ex.getMessage(), ex); throw ExceptionUtils.toBadRequestException(null, null); } }
Example #20
Source File: IssueSamlClaimsUnitTest.java From cxf with Apache License 2.0 | 5 votes |
private Element createSAMLAssertion( String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler, Map<String, RealmProperties> realms ) throws WSSecurityException { SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider(); samlTokenProvider.setRealmMap(realms); List<AttributeStatementProvider> customProviderList = new ArrayList<>(); customProviderList.add(new ClaimsAttributeStatementProvider()); samlTokenProvider.setAttributeStatementProviders(customProviderList); TokenProviderParameters providerParameters = createProviderParameters( tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername, callbackHandler ); if (realms != null) { providerParameters.setRealm("A"); } // Set the ClaimsManager ClaimsManager claimsManager = new ClaimsManager(); ClaimsHandler claimsHandler = new CustomClaimsHandler(); claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler)); providerParameters.setClaimsManager(claimsManager); ClaimCollection requestedClaims = new ClaimCollection(); Claim requestClaim = new Claim(); requestClaim.setClaimType(ClaimTypes.LASTNAME); requestClaim.setOptional(false); requestedClaims.add(requestClaim); providerParameters.setRequestedSecondaryClaims(requestedClaims); TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters); assertNotNull(providerResponse); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); return (Element)providerResponse.getToken(); }
Example #21
Source File: PolicyBasedWSS4JStaxOutInterceptor.java From cxf with Apache License 2.0 | 5 votes |
private void checkAsymmetricBinding( SoapMessage message, WSSSecurityProperties securityProperties ) throws WSSecurityException { Object s = SecurityUtils.getSecurityPropertyValue(SecurityConstants.SIGNATURE_CRYPTO, message); if (s == null) { s = SecurityUtils.getSecurityPropertyValue(SecurityConstants.SIGNATURE_PROPERTIES, message); } Object e = SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_CRYPTO, message); if (e == null) { e = SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_PROPERTIES, message); } Crypto encrCrypto = getEncryptionCrypto(e, message, securityProperties); Crypto signCrypto = null; if (e != null && e.equals(s)) { signCrypto = encrCrypto; } else { signCrypto = getSignatureCrypto(s, message, securityProperties); } if (signCrypto != null) { securityProperties.setSignatureCrypto(signCrypto); } if (encrCrypto != null) { securityProperties.setEncryptionCrypto(encrCrypto); } else if (signCrypto != null) { securityProperties.setEncryptionCrypto(signCrypto); } }
Example #22
Source File: AbstractXmlSigInHandler.java From cxf with Apache License 2.0 | 5 votes |
protected String getUserName(Crypto crypto, Message message) { SecurityContext sc = message.get(SecurityContext.class); if (sc != null && sc.getUserPrincipal() != null) { return sc.getUserPrincipal().getName(); } return RSSecurityUtils.getUserName(crypto, null); }
Example #23
Source File: SAMLTokenRenewerRealmTest.java From cxf with Apache License 2.0 | 5 votes |
private TokenValidatorParameters createValidatorParameters() throws WSSecurityException { TokenValidatorParameters parameters = new TokenValidatorParameters(); TokenRequirements tokenRequirements = new TokenRequirements(); tokenRequirements.setTokenType(STSConstants.STATUS); parameters.setTokenRequirements(tokenRequirements); KeyRequirements keyRequirements = new KeyRequirements(); parameters.setKeyRequirements(keyRequirements); parameters.setPrincipal(new CustomTokenPrincipal("alice")); // Mock up message context MessageImpl msg = new MessageImpl(); WrappedMessageContext msgCtx = new WrappedMessageContext(msg); parameters.setMessageContext(msgCtx); // Add STSProperties object StaticSTSProperties 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-2"); parameters.setStsProperties(stsProperties); parameters.setTokenStore(tokenStore); return parameters; }
Example #24
Source File: XmlSecInInterceptor.java From cxf with Apache License 2.0 | 5 votes |
private void prepareMessage(Message inMsg) throws Fault { XMLStreamReader originalXmlStreamReader = inMsg.getContent(XMLStreamReader.class); if (originalXmlStreamReader == null) { InputStream is = inMsg.getContent(InputStream.class); if (is != null) { originalXmlStreamReader = StaxUtils.createXMLStreamReader(is); } } try { XMLSecurityProperties properties = new XMLSecurityProperties(); configureDecryptionKeys(inMsg, properties); Crypto signatureCrypto = getSignatureCrypto(inMsg); configureSignatureKeys(signatureCrypto, inMsg, properties); SecurityEventListener securityEventListener = configureSecurityEventListener(signatureCrypto, inMsg, properties); InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties); XMLStreamReader newXmlStreamReader = inboundXMLSec.processInMessage(originalXmlStreamReader, null, securityEventListener); inMsg.setContent(XMLStreamReader.class, newXmlStreamReader); } catch (XMLStreamException | XMLSecurityException | IOException | UnsupportedCallbackException e) { throwFault(e.getMessage(), e); } }
Example #25
Source File: SAMLTokenRenewerLifetimeTest.java From cxf with Apache License 2.0 | 5 votes |
/** * Renew SAML 2 token with a lifetime configured in SAMLTokenProvider * No specific lifetime requested */ @org.junit.Test public void testSaml2ProviderLifetime() throws Exception { SAMLTokenRenewer samlTokenRenewer = new SAMLTokenRenewer(); samlTokenRenewer.setVerifyProofOfPossession(false); samlTokenRenewer.setAllowRenewalAfterExpiry(true); long providerLifetime = 10 * 600L; DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider(); conditionsProvider.setLifetime(providerLifetime); samlTokenRenewer.setConditionsProvider(conditionsProvider); TokenRenewerParameters renewerParameters = createRenewerParameters(); 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)); TokenRenewerResponse renewerResponse = samlTokenRenewer.renewToken(renewerParameters); assertNotNull(renewerResponse); assertNotNull(renewerResponse.getToken()); long duration = Duration.between(renewerResponse.getCreated(), renewerResponse.getExpires()).getSeconds(); assertEquals(providerLifetime, duration); }
Example #26
Source File: RenewSamlUnitTest.java From cxf with Apache License 2.0 | 5 votes |
private Element createSAMLAssertion( String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler, long ttlMs, boolean allowRenewing, boolean allowRenewingAfterExpiry ) throws WSSecurityException { SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider(); DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider(); conditionsProvider.setAcceptClientLifetime(true); samlTokenProvider.setConditionsProvider(conditionsProvider); TokenProviderParameters providerParameters = createProviderParameters( tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername, callbackHandler ); Renewing renewing = new Renewing(); renewing.setAllowRenewing(allowRenewing); renewing.setAllowRenewingAfterExpiry(allowRenewingAfterExpiry); providerParameters.getTokenRequirements().setRenewing(renewing); if (ttlMs != 0) { Lifetime lifetime = new Lifetime(); Instant creationTime = Instant.now(); Instant expirationTime = creationTime.plusNanos(ttlMs * 1000000L); lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true))); lifetime.setExpires(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true))); providerParameters.getTokenRequirements().setLifetime(lifetime); } TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters); assertNotNull(providerResponse); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); return (Element)providerResponse.getToken(); }
Example #27
Source File: XmlSecInInterceptor.java From cxf with Apache License 2.0 | 5 votes |
private void configureDecryptionKeys(Message message, XMLSecurityProperties properties) throws IOException, UnsupportedCallbackException, WSSecurityException { String cryptoKey = null; String propKey = null; if (RSSecurityUtils.isSignedAndEncryptedTwoWay(message)) { cryptoKey = SecurityConstants.SIGNATURE_CRYPTO; propKey = SecurityConstants.SIGNATURE_PROPERTIES; } else { cryptoKey = SecurityConstants.ENCRYPT_CRYPTO; propKey = SecurityConstants.ENCRYPT_PROPERTIES; } Crypto crypto = null; try { crypto = new CryptoLoader().getCrypto(message, cryptoKey, propKey); } catch (Exception ex) { throwFault("Crypto can not be loaded", ex); } if (crypto != null) { String alias = decryptionAlias; if (alias == null) { alias = crypto.getDefaultX509Identifier(); } if (alias != null) { CallbackHandler callback = RSSecurityUtils.getCallbackHandler(message, this.getClass()); WSPasswordCallback passwordCallback = new WSPasswordCallback(alias, WSPasswordCallback.DECRYPT); callback.handle(new Callback[] {passwordCallback}); Key privateKey = crypto.getPrivateKey(alias, passwordCallback.getPassword()); properties.setDecryptionKey(privateKey); } } }
Example #28
Source File: SAMLTokenValidatorCachedRealmTest.java From cxf with Apache License 2.0 | 5 votes |
private TokenValidatorParameters createValidatorParameters() throws WSSecurityException { TokenValidatorParameters parameters = new TokenValidatorParameters(); TokenRequirements tokenRequirements = new TokenRequirements(); tokenRequirements.setTokenType(STSConstants.STATUS); parameters.setTokenRequirements(tokenRequirements); KeyRequirements keyRequirements = new KeyRequirements(); parameters.setKeyRequirements(keyRequirements); parameters.setPrincipal(new CustomTokenPrincipal("alice")); // Mock up message context MessageImpl msg = new MessageImpl(); WrappedMessageContext msgCtx = new WrappedMessageContext(msg); parameters.setMessageContext(msgCtx); // Add STSProperties object StaticSTSProperties 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-2"); parameters.setStsProperties(stsProperties); parameters.setTokenStore(tokenStore); return parameters; }
Example #29
Source File: RenewSamlUnitTest.java From cxf with Apache License 2.0 | 5 votes |
private TokenProviderParameters createProviderParameters( String tokenType, String keyType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler ) throws WSSecurityException { TokenProviderParameters parameters = new TokenProviderParameters(); TokenRequirements tokenRequirements = new TokenRequirements(); tokenRequirements.setTokenType(tokenType); parameters.setTokenRequirements(tokenRequirements); KeyRequirements keyRequirements = new KeyRequirements(); keyRequirements.setKeyType(keyType); parameters.setKeyRequirements(keyRequirements); parameters.setPrincipal(new CustomTokenPrincipal("alice")); // Mock up message context MessageImpl msg = new MessageImpl(); WrappedMessageContext msgCtx = new WrappedMessageContext(msg); parameters.setMessageContext(msgCtx); parameters.setAppliesToAddress("http://dummy-service.com/dummy"); // Add STSProperties object StaticSTSProperties stsProperties = new StaticSTSProperties(); stsProperties.setSignatureCrypto(crypto); stsProperties.setSignatureUsername(signatureUsername); stsProperties.setCallbackHandler(callbackHandler); stsProperties.setIssuer("STS"); parameters.setStsProperties(stsProperties); parameters.setEncryptionProperties(new EncryptionProperties()); parameters.setTokenStore(tokenStore); return parameters; }
Example #30
Source File: Saml2CallbackHandler.java From cxf with Apache License 2.0 | 5 votes |
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof SAMLCallback) { SAMLCallback callback = (SAMLCallback) callbacks[i]; callback.setSamlVersion(Version.SAML_20); callback.setIssuer("intermediary"); String subjectName = "uid=" + principal.getName(); String confirmationMethod = SAML2Constants.CONF_SENDER_VOUCHES; SubjectBean subjectBean = new SubjectBean(subjectName, null, confirmationMethod); callback.setSubject(subjectBean); AttributeStatementBean attrBean = new AttributeStatementBean(); if (subjectBean != null) { attrBean.setSubject(subjectBean); } AttributeBean attributeBean = new AttributeBean(); attributeBean.setQualifiedName("role"); attributeBean.addAttributeValue("user"); attrBean.setSamlAttributes(Collections.singletonList(attributeBean)); callback.setAttributeStatementData(Collections.singletonList(attrBean)); try { String file = "serviceKeystore.properties"; Crypto crypto = CryptoFactory.getInstance(file); callback.setIssuerCrypto(crypto); callback.setIssuerKeyName("myservicekey"); callback.setIssuerKeyPassword("skpass"); callback.setSignAssertion(true); } catch (WSSecurityException e) { throw new IOException(e); } } } }