use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.
the class CancelSCTUnitTest method testCancelSCT.
/**
* Test to successfully cancel a SecurityContextToken
*/
@org.junit.Test
public void testCancelSCT() throws Exception {
TokenCancelOperation cancelOperation = new TokenCancelOperation();
cancelOperation.setTokenStore(tokenStore);
// Add Token Canceller
TokenCanceller sctCanceller = new SCTCanceller();
sctCanceller.setVerifyProofOfPossession(false);
cancelOperation.setTokenCancellers(Collections.singletonList(sctCanceller));
// 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");
cancelOperation.setStsProperties(stsProperties);
// Get a SecurityContextToken via the SCTProvider
TokenProviderResponse providerResponse = createSCT();
Element sct = (Element) providerResponse.getToken();
CancelTargetType cancelTarget = new CancelTargetType();
cancelTarget.setAny(sct);
// Mock up a request
JAXBElement<CancelTargetType> cancelTargetType = new JAXBElement<CancelTargetType>(QNameConstants.CANCEL_TARGET, CancelTargetType.class, cancelTarget);
RequestSecurityTokenType request = new RequestSecurityTokenType();
request.getAny().add(cancelTargetType);
// 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));
// Cancel a token
RequestSecurityTokenResponseType response = cancelOperation.cancel(request, principal, msgCtx);
assertTrue(validateResponse(response));
// Now try to cancel again
try {
cancelOperation.cancel(request, principal, msgCtx);
} catch (STSException ex) {
// expected
}
}
use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.
the class DefaultConditionsProvider method getConditions.
/**
* Get a ConditionsBean object.
*/
@Override
public ConditionsBean getConditions(TokenProviderParameters providerParameters) {
ConditionsBean conditions = new ConditionsBean();
Lifetime tokenLifetime = providerParameters.getTokenRequirements().getLifetime();
if (lifetime > 0) {
if (acceptClientLifetime && tokenLifetime != null && (tokenLifetime.getCreated() != null || tokenLifetime.getExpires() != null)) {
Instant creationTime = parsedInstantOrDefault(tokenLifetime.getCreated(), Instant.now());
Instant expirationTime = parsedInstantOrDefault(tokenLifetime.getExpires(), creationTime.plusSeconds(lifetime));
// Check to see if the created time is in the future
Instant validCreation = Instant.now();
if (futureTimeToLive > 0) {
validCreation = validCreation.plusSeconds(futureTimeToLive);
}
if (creationTime.isAfter(validCreation)) {
LOG.fine("The Created Time is too far in the future");
throw new STSException("The Created Time is too far in the future", STSException.INVALID_TIME);
}
long requestedLifetime = Duration.between(creationTime, expirationTime).getSeconds();
if (requestedLifetime > getMaxLifetime()) {
StringBuilder sb = new StringBuilder();
sb.append("Requested lifetime [").append(requestedLifetime);
sb.append(" sec] exceed configured maximum lifetime [").append(getMaxLifetime());
sb.append(" sec]");
LOG.warning(sb.toString());
if (isFailLifetimeExceedance()) {
throw new STSException("Requested lifetime exceeds maximum lifetime", STSException.INVALID_TIME);
}
expirationTime = creationTime.plusSeconds(getMaxLifetime());
}
conditions.setNotAfter(expirationTime);
conditions.setNotBefore(creationTime);
} else {
conditions.setTokenPeriodSeconds(lifetime);
}
} else {
conditions.setTokenPeriodMinutes(5);
}
List<AudienceRestrictionBean> audienceRestrictions = createAudienceRestrictions(providerParameters);
if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
conditions.setAudienceRestrictions(audienceRestrictions);
}
return conditions;
}
use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.
the class SAMLTokenProvider method testKeyType.
/**
* Do some tests on the KeyType parameter.
*/
private void testKeyType(TokenProviderParameters tokenParameters) {
KeyRequirements keyRequirements = tokenParameters.getKeyRequirements();
String keyType = keyRequirements.getKeyType();
if (STSConstants.PUBLIC_KEY_KEYTYPE.equals(keyType)) {
if (keyRequirements.getReceivedCredential() == null || (keyRequirements.getReceivedCredential().getX509Cert() == null && keyRequirements.getReceivedCredential().getPublicKey() == null)) {
LOG.log(Level.WARNING, "A PublicKey Keytype is requested, but no certificate is provided");
throw new STSException("No client certificate for PublicKey KeyType", STSException.INVALID_REQUEST);
}
} else if (!STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyType) && !STSConstants.BEARER_KEY_KEYTYPE.equals(keyType) && keyType != null) {
LOG.log(Level.WARNING, "An unknown KeyType was requested: " + keyType);
throw new STSException("Unknown KeyType", STSException.INVALID_REQUEST);
}
}
use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.
the class SAMLTokenProvider method createToken.
/**
* Create a token given a TokenProviderParameters
*/
public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
testKeyType(tokenParameters);
KeyRequirements keyRequirements = tokenParameters.getKeyRequirements();
TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Handling token of type: " + tokenRequirements.getTokenType());
}
byte[] secret = null;
byte[] entropyBytes = null;
long keySize = 0;
boolean computedKey = false;
if (STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyRequirements.getKeyType())) {
SymmetricKeyHandler keyHandler = new SymmetricKeyHandler(tokenParameters);
keyHandler.createSymmetricKey();
secret = keyHandler.getSecret();
entropyBytes = keyHandler.getEntropyBytes();
keySize = keyHandler.getKeySize();
computedKey = keyHandler.isComputedKey();
}
try {
Document doc = DOMUtils.createDocument();
SamlAssertionWrapper assertion = createSamlToken(tokenParameters, secret, doc);
Element token = assertion.toDOM(doc);
// set the token in cache (only if the token is signed)
byte[] signatureValue = assertion.getSignatureValue();
if (tokenParameters.getTokenStore() != null && signatureValue != null && signatureValue.length > 0) {
SecurityToken securityToken = CacheUtils.createSecurityTokenForStorage(token, assertion.getId(), assertion.getNotOnOrAfter(), tokenParameters.getPrincipal(), tokenParameters.getRealm(), tokenParameters.getTokenRequirements().getRenewing());
CacheUtils.storeTokenInCache(securityToken, tokenParameters.getTokenStore(), signatureValue);
}
TokenProviderResponse response = new TokenProviderResponse();
String tokenType = tokenRequirements.getTokenType();
if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
response.setTokenId(token.getAttributeNS(null, "ID"));
} else {
response.setTokenId(token.getAttributeNS(null, "AssertionID"));
}
if (tokenParameters.isEncryptToken()) {
token = TokenProviderUtils.encryptToken(token, response.getTokenId(), tokenParameters.getStsProperties(), tokenParameters.getEncryptionProperties(), keyRequirements, tokenParameters.getMessageContext());
}
response.setToken(token);
final DateTime validFrom;
final DateTime validTill;
if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
validFrom = assertion.getSaml2().getConditions().getNotBefore();
validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
} else {
validFrom = assertion.getSaml1().getConditions().getNotBefore();
validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
}
response.setCreated(validFrom.toDate().toInstant());
response.setExpires(validTill.toDate().toInstant());
response.setEntropy(entropyBytes);
if (keySize > 0) {
response.setKeySize(keySize);
}
response.setComputedKey(computedKey);
LOG.fine("SAML Token successfully created");
if (secret != null) {
Arrays.fill(secret, (byte) 0);
}
return response;
} catch (Exception e) {
LOG.log(Level.WARNING, "", e);
throw new STSException("Can't serialize SAML assertion", e, STSException.REQUEST_FAILED);
}
}
use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.
the class SymmetricKeyHandler method createSymmetricKey.
/**
* Create the Symmetric Key
*/
public void createSymmetricKey() {
computedKey = false;
boolean generateEntropy = true;
if (clientEntropy != null) {
BinarySecret binarySecret = clientEntropy.getBinarySecret();
if (binarySecret != null && (STSConstants.SYMMETRIC_KEY_TYPE.equals(binarySecret.getBinarySecretType()) || binarySecret.getBinarySecretType() == null)) {
secret = binarySecret.getBinarySecretValue();
generateEntropy = false;
} else if (clientEntropy.getDecryptedKey() != null) {
secret = clientEntropy.getDecryptedKey();
generateEntropy = false;
}
}
if (generateEntropy) {
try {
entropyBytes = WSSecurityUtil.generateNonce(keySize / 8);
secret = entropyBytes;
} catch (WSSecurityException ex) {
LOG.log(Level.WARNING, "", ex);
throw new STSException("Error in creating symmetric key", ex, STSException.INVALID_REQUEST);
}
if (clientEntropy != null && clientEntropy.getBinarySecret() != null) {
byte[] nonce = clientEntropy.getBinarySecret().getBinarySecretValue();
try {
P_SHA1 psha1 = new P_SHA1();
secret = psha1.createKey(nonce, entropyBytes, 0, keySize / 8);
computedKey = true;
} catch (WSSecurityException ex) {
LOG.log(Level.WARNING, "", ex);
throw new STSException("Error in creating symmetric key", STSException.INVALID_REQUEST);
}
}
}
}
Aggregations