Java Code Examples for org.apache.wss4j.common.crypto.Crypto#getX509Certificates()
The following examples show how to use
org.apache.wss4j.common.crypto.Crypto#getX509Certificates() .
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: SamlCallbackHandler.java From cxf with Apache License 2.0 | 6 votes |
protected KeyInfoBean createKeyInfo() throws Exception { Crypto crypto = CryptoFactory.getInstance(cryptoPropertiesFile); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(cryptoAlias); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); KeyInfoBean keyInfo = new KeyInfoBean(); keyInfo.setCertIdentifer(keyInfoIdentifier); if (keyInfoIdentifier == CERT_IDENTIFIER.X509_CERT) { keyInfo.setCertificate(certs[0]); } else if (keyInfoIdentifier == CERT_IDENTIFIER.KEY_VALUE) { keyInfo.setPublicKey(certs[0].getPublicKey()); } return keyInfo; }
Example 2
Source File: CertsUtils.java From cxf-fediz with Apache License 2.0 | 6 votes |
/** * Load an X.509 Certificate from a WSS4J Crypto instance using a keystore alias */ public static X509Certificate getX509CertificateFromCrypto(Crypto crypto, String keyAlias) throws WSSecurityException { if (keyAlias == null || "".equals(keyAlias)) { keyAlias = crypto.getDefaultX509Identifier(); } if (keyAlias == null) { throw new RuntimeException("No keystore alias was specified to sign the metadata"); } CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(keyAlias); X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType); if (issuerCerts == null || issuerCerts.length == 0) { throw new RuntimeException( "No issuer certs were found to sign the metadata using issuer name: " + keyAlias); } return issuerCerts[0]; }
Example 3
Source File: SamlCallbackHandler.java From cxf with Apache License 2.0 | 6 votes |
protected KeyInfoBean createKeyInfo() throws Exception { Crypto crypto = CryptoFactory.getInstance(cryptoPropertiesFile); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(cryptoAlias); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); KeyInfoBean keyInfo = new KeyInfoBean(); keyInfo.setCertIdentifer(keyInfoIdentifier); if (keyInfoIdentifier == CERT_IDENTIFIER.X509_CERT) { keyInfo.setCertificate(certs[0]); } else if (keyInfoIdentifier == CERT_IDENTIFIER.KEY_VALUE) { keyInfo.setPublicKey(certs[0].getPublicKey()); } return keyInfo; }
Example 4
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 5
Source File: SamlRoleCallbackHandler.java From cxf with Apache License 2.0 | 6 votes |
protected KeyInfoBean createKeyInfo() throws Exception { Crypto crypto = CryptoFactory.getInstance("alice.properties"); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("alice"); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); KeyInfoBean keyInfo = new KeyInfoBean(); keyInfo.setCertIdentifer(keyInfoIdentifier); if (keyInfoIdentifier == CERT_IDENTIFIER.X509_CERT) { keyInfo.setCertificate(certs[0]); } else if (keyInfoIdentifier == CERT_IDENTIFIER.KEY_VALUE) { keyInfo.setPublicKey(certs[0].getPublicKey()); } return keyInfo; }
Example 6
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 7
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 8
Source File: AbstractBindingBuilder.java From cxf with Apache License 2.0 | 5 votes |
public Crypto getEncryptionCrypto() throws WSSecurityException { Crypto crypto = getCrypto(SecurityConstants.ENCRYPT_CRYPTO, SecurityConstants.ENCRYPT_PROPERTIES); boolean enableRevocation = false; String enableRevStr = (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENABLE_REVOCATION, message); if (enableRevStr != null) { enableRevocation = Boolean.parseBoolean(enableRevStr); } if (enableRevocation && crypto != null) { CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); String encrUser = (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_USERNAME, message); if (encrUser == null) { try { encrUser = crypto.getDefaultX509Identifier(); } catch (WSSecurityException e1) { throw new Fault(e1); } } cryptoType.setAlias(encrUser); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); if (certs != null && certs.length > 0) { crypto.verifyTrust(certs, enableRevocation, null, null); } } if (crypto != null) { this.message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto); } return crypto; }
Example 9
Source File: SAML2CallbackHandler.java From cxf with Apache License 2.0 | 5 votes |
public SAML2CallbackHandler() throws Exception { if (certs == null) { Crypto crypto = CryptoFactory.getInstance("alice.properties"); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("alice"); certs = crypto.getX509Certificates(cryptoType); } subjectName = "uid=alice,ou=people,ou=saml-demo,o=example.com"; subjectQualifier = "www.example.com"; confirmationMethod = SAML2Constants.CONF_SENDER_VOUCHES; }
Example 10
Source File: JWTTokenProviderTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testCreateSignedJWT() throws Exception { TokenProvider jwtTokenProvider = new JWTTokenProvider(); ((JWTTokenProvider)jwtTokenProvider).setSignToken(true); TokenProviderParameters providerParameters = createProviderParameters(); assertTrue(jwtTokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE)); TokenProviderResponse providerResponse = jwtTokenProvider.createToken(providerParameters); assertNotNull(providerResponse); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); String token = (String)providerResponse.getToken(); assertNotNull(token); assertTrue(token.split("\\.").length == 3); // Validate the token JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token); JwtToken jwt = jwtConsumer.getJwtToken(); Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT)); Assert.assertEquals(providerResponse.getTokenId(), jwt.getClaim(JwtConstants.CLAIM_JWT_ID)); Assert.assertEquals(providerResponse.getCreated().getEpochSecond(), jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT)); Assert.assertEquals(providerResponse.getExpires().getEpochSecond(), jwt.getClaim(JwtConstants.CLAIM_EXPIRY)); // Verify Signature Crypto crypto = providerParameters.getStsProperties().getSignatureCrypto(); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(providerParameters.getStsProperties().getSignatureUsername()); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); assertNotNull(certs); assertTrue(jwtConsumer.verifySignatureWith(certs[0], SignatureAlgorithm.RS256)); }
Example 11
Source File: RSSecurityUtils.java From cxf with Apache License 2.0 | 5 votes |
public static X509Certificate[] getCertificates(Crypto crypto, String user) throws Exception { if (crypto == null) { throw new Exception("Crypto instance is null"); } CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(user); X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType); if (issuerCerts == null || issuerCerts.length == 0) { throw new Exception( "No issuer certs were found using issuer name: " + user); } return issuerCerts; }
Example 12
Source File: X509TokenValidatorTest.java From cxf with Apache License 2.0 | 5 votes |
/** * Test an invalid certificate */ @org.junit.Test public void testInvalidCertificate() throws Exception { TokenValidator x509TokenValidator = new X509TokenValidator(); TokenValidatorParameters validatorParameters = createValidatorParameters(); TokenRequirements tokenRequirements = validatorParameters.getTokenRequirements(); // Create a ValidateTarget consisting of an X509Certificate BinarySecurityTokenType binarySecurityToken = new BinarySecurityTokenType(); JAXBElement<BinarySecurityTokenType> tokenType = new JAXBElement<BinarySecurityTokenType>( QNameConstants.BINARY_SECURITY_TOKEN, BinarySecurityTokenType.class, binarySecurityToken ); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("eve"); Crypto crypto = CryptoFactory.getInstance(getEveCryptoProperties()); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); assertTrue(certs != null && certs.length > 0); binarySecurityToken.setValue(Base64.getMimeEncoder().encodeToString(certs[0].getEncoded())); binarySecurityToken.setValueType(X509TokenValidator.X509_V3_TYPE); binarySecurityToken.setEncodingType(WSS4JConstants.SOAPMESSAGE_NS + "#Base64Binary"); ReceivedToken validateTarget = new ReceivedToken(tokenType); tokenRequirements.setValidateTarget(validateTarget); validatorParameters.setToken(validateTarget); assertTrue(x509TokenValidator.canHandleToken(validateTarget)); TokenValidatorResponse validatorResponse = x509TokenValidator.validateToken(validatorParameters); assertNotNull(validatorResponse); assertNotNull(validatorResponse.getToken()); assertTrue(validatorResponse.getToken().getState() == STATE.INVALID); }
Example 13
Source File: IssueJWTRealmUnitTest.java From cxf with Apache License 2.0 | 5 votes |
private void validateToken(String token, String issuer, String sigUsername, Crypto sigCrypto) throws Exception { JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token); JwtToken jwt = jwtConsumer.getJwtToken(); Assert.assertEquals(issuer, jwt.getClaim(JwtConstants.CLAIM_ISSUER)); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(sigUsername); X509Certificate[] certs = sigCrypto.getX509Certificates(cryptoType); assertNotNull(certs); assertTrue(jwtConsumer.verifySignatureWith(certs[0], SignatureAlgorithm.RS256)); }
Example 14
Source File: SAML2CallbackHandler.java From cxf with Apache License 2.0 | 5 votes |
public SAML2CallbackHandler() throws Exception { if (certs == null) { Crypto crypto = CryptoFactory.getInstance("alice.properties"); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("alice"); certs = crypto.getX509Certificates(cryptoType); } subjectName = "uid=joe,ou=people,ou=saml-demo,o=example.com"; subjectQualifier = "www.example.com"; confirmationMethod = SAML2Constants.CONF_SENDER_VOUCHES; }
Example 15
Source File: SAMLResponseValidatorTest.java From cxf with Apache License 2.0 | 4 votes |
/** * Sign a SAML Response * @throws Exception */ private void signResponse( Response response, String issuerKeyName, String issuerKeyPassword, Crypto issuerCrypto, boolean useKeyInfo ) throws Exception { // // Create the signature // Signature signature = OpenSAMLUtil.buildSignature(); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); // prepare to sign the SAML token CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(issuerKeyName); X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType); if (issuerCerts == null) { throw new Exception( "No issuer certs were found to sign the SAML Assertion using issuer name: " + issuerKeyName); } String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); if ("DSA".equalsIgnoreCase(pubKeyAlgo)) { sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA; } PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword); signature.setSignatureAlgorithm(sigAlgo); BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey); signature.setSigningCredential(signingCredential); if (useKeyInfo) { X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory(); kiFactory.setEmitEntityCertificate(true); try { KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential); signature.setKeyInfo(keyInfo); } catch (org.opensaml.security.SecurityException ex) { throw new Exception( "Error generating KeyInfo from signing credential", ex); } } // add the signature to the assertion SignableSAMLObject signableObject = response; signableObject.setSignature(signature); signableObject.releaseDOM(); signableObject.releaseChildrenDOM(true); }
Example 16
Source File: SamlRedirectBindingFilter.java From cxf with Apache License 2.0 | 4 votes |
/** * Sign a request according to the redirect binding spec for Web SSO */ private void signRequest( String authnRequest, String relayState, UriBuilder ub ) throws Exception { Crypto crypto = getSignatureCrypto(); if (crypto == null) { LOG.warning("No crypto instance of properties file configured for signature"); throw ExceptionUtils.toInternalServerErrorException(null, null); } String signatureUser = getSignatureUsername(); if (signatureUser == null) { LOG.warning("No user configured for signature"); throw ExceptionUtils.toInternalServerErrorException(null, null); } CallbackHandler callbackHandler = getCallbackHandler(); if (callbackHandler == null) { LOG.warning("No CallbackHandler configured to supply a password for signature"); throw ExceptionUtils.toInternalServerErrorException(null, null); } CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(signatureUser); X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType); if (issuerCerts == null) { throw new Exception( "No issuer certs were found to sign the request using name: " + signatureUser ); } String sigAlgo = getSignatureAlgorithm(); String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); LOG.fine("automatic sig algo detection: " + pubKeyAlgo); if ("DSA".equalsIgnoreCase(pubKeyAlgo)) { sigAlgo = SSOConstants.DSA_SHA1; } LOG.fine("Using Signature algorithm " + sigAlgo); ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name())); // Get the password WSPasswordCallback[] cb = {new WSPasswordCallback(signatureUser, WSPasswordCallback.SIGNATURE)}; callbackHandler.handle(cb); String password = cb[0].getPassword(); // Get the private key PrivateKey privateKey = crypto.getPrivateKey(signatureUser, password); // Sign the request String jceSigAlgo = JCEMapper.translateURItoJCEID(sigAlgo); Signature signature = Signature.getInstance(jceSigAlgo); signature.initSign(privateKey); String requestToSign = SSOConstants.SAML_REQUEST + "=" + authnRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name()); signature.update(requestToSign.getBytes(StandardCharsets.UTF_8)); byte[] signBytes = signature.sign(); String encodedSignature = Base64.getEncoder().encodeToString(signBytes); // Clean the private key from memory when we're done try { privateKey.destroy(); } catch (DestroyFailedException ex) { // ignore } ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name())); }
Example 17
Source File: IssueJWTOnbehalfofUnitTest.java From cxf with Apache License 2.0 | 4 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); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("myclientkey"); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); ReceivedCredential receivedCredential = new ReceivedCredential(); receivedCredential.setX509Cert(certs[0]); keyRequirements.setReceivedCredential(receivedCredential); 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"); stsProperties.setEncryptionUsername("myservicekey"); stsProperties.setEncryptionCrypto(crypto); parameters.setStsProperties(stsProperties); parameters.setEncryptionProperties(new EncryptionProperties()); return parameters; }
Example 18
Source File: SAMLSSOResponseValidatorTest.java From cxf with Apache License 2.0 | 4 votes |
/** * Sign a SAML Response * @throws Exception */ private void signResponse( Response response, String issuerKeyName, String issuerKeyPassword, Crypto issuerCrypto, boolean useKeyInfo ) throws Exception { // // Create the signature // Signature signature = OpenSAMLUtil.buildSignature(); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); // prepare to sign the SAML token CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(issuerKeyName); X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType); if (issuerCerts == null) { throw new Exception( "No issuer certs were found to sign the SAML Assertion using issuer name: " + issuerKeyName); } String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); if ("DSA".equalsIgnoreCase(pubKeyAlgo)) { sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA; } PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword); signature.setSignatureAlgorithm(sigAlgo); BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey); signature.setSigningCredential(signingCredential); if (useKeyInfo) { X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory(); kiFactory.setEmitEntityCertificate(true); try { KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential); signature.setKeyInfo(keyInfo); } catch (org.opensaml.security.SecurityException ex) { throw new Exception( "Error generating KeyInfo from signing credential", ex); } } // add the signature to the assertion SignableSAMLObject signableObject = response; signableObject.setSignature(signature); signableObject.releaseDOM(); signableObject.releaseChildrenDOM(true); }
Example 19
Source File: JWTTokenProviderTest.java From cxf with Apache License 2.0 | 4 votes |
@org.junit.Test public void testCreateSignedPSJWT() throws Exception { try { Security.addProvider(new BouncyCastleProvider()); TokenProvider jwtTokenProvider = new JWTTokenProvider(); ((JWTTokenProvider)jwtTokenProvider).setSignToken(true); TokenProviderParameters providerParameters = createProviderParameters(); SignatureProperties sigProps = new SignatureProperties(); sigProps.setSignatureAlgorithm(SignatureAlgorithm.PS256.name()); providerParameters.getStsProperties().setSignatureProperties(sigProps); assertTrue(jwtTokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE)); TokenProviderResponse providerResponse = jwtTokenProvider.createToken(providerParameters); assertNotNull(providerResponse); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); String token = (String)providerResponse.getToken(); assertNotNull(token); assertTrue(token.split("\\.").length == 3); // Validate the token JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token); JwtToken jwt = jwtConsumer.getJwtToken(); Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT)); Assert.assertEquals(providerResponse.getTokenId(), jwt.getClaim(JwtConstants.CLAIM_JWT_ID)); Assert.assertEquals(providerResponse.getCreated().getEpochSecond(), jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT)); Assert.assertEquals(providerResponse.getExpires().getEpochSecond(), jwt.getClaim(JwtConstants.CLAIM_EXPIRY)); // Verify Signature Crypto crypto = providerParameters.getStsProperties().getSignatureCrypto(); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(providerParameters.getStsProperties().getSignatureUsername()); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); assertNotNull(certs); assertFalse(jwtConsumer.verifySignatureWith(certs[0], SignatureAlgorithm.RS256)); assertTrue(jwtConsumer.verifySignatureWith(certs[0], SignatureAlgorithm.PS256)); } finally { Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); } }
Example 20
Source File: ValidateX509TokenUnitTest.java From cxf with Apache License 2.0 | 4 votes |
/** * Test to successfully validate an X.509 token */ @org.junit.Test public void testValidateX509Token() throws Exception { TokenValidateOperation validateOperation = new TokenValidateOperation(); // Add Token Validator List<TokenValidator> validatorList = new ArrayList<>(); validatorList.add(new X509TokenValidator()); validateOperation.setTokenValidators(validatorList); // 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"); validateOperation.setStsProperties(stsProperties); // Mock up a request RequestSecurityTokenType request = new RequestSecurityTokenType(); JAXBElement<String> tokenType = new JAXBElement<String>( QNameConstants.TOKEN_TYPE, String.class, STSConstants.STATUS ); request.getAny().add(tokenType); // Create a BinarySecurityToken CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("myclientkey"); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); assertTrue(certs != null && certs.length > 0); JAXBElement<BinarySecurityTokenType> binarySecurityTokenType = createBinarySecurityToken(certs[0]); ValidateTargetType validateTarget = new ValidateTargetType(); validateTarget.setAny(binarySecurityTokenType); 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) ); // Validate a token RequestSecurityTokenResponseType response = validateOperation.validate(request, principal, msgCtx); assertTrue(validateResponse(response)); }