use of org.apache.cxf.sts.request.ReceivedToken in project ddf by codice.
the class TestBSTDelegationHandler method testDelegationAllowed.
@Test
public void testDelegationAllowed() {
BinarySecurityTokenType binarySecurityTokenType = new BinarySecurityTokenType();
binarySecurityTokenType.setEncodingType(WSConstants.SOAPMESSAGE_NS + "#Base64Binary");
binarySecurityTokenType.setValueType(BSTAuthenticationToken.BST_NS + "#" + BSTAuthenticationToken.BST_LN);
ReceivedToken receivedToken = mock(ReceivedToken.class);
when(receivedToken.getToken()).thenReturn(binarySecurityTokenType);
TokenDelegationParameters tokenDelegationParameters = mock(TokenDelegationParameters.class);
when(tokenDelegationParameters.getToken()).thenReturn(receivedToken);
BSTDelegationHandler bstDelegationHandler = new BSTDelegationHandler();
TokenDelegationResponse response = bstDelegationHandler.isDelegationAllowed(tokenDelegationParameters);
assertEquals(true, response.isDelegationAllowed());
}
use of org.apache.cxf.sts.request.ReceivedToken in project ddf by codice.
the class WebSSOTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*/
@Override
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.debug("Validating SSO Token");
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
Crypto sigCrypto = stsProperties.getSignatureCrypto();
CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(sigCrypto);
WSSConfig wssConfig = WSSConfig.getNewInstance();
requestData.setWssConfig(wssConfig);
requestData.setCallbackHandler(callbackHandler);
LOGGER.debug("Setting validate state to invalid before check.");
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
if (!validateTarget.isBinarySecurityToken()) {
LOGGER.debug("Validate target is not a binary security token, returning invalid response.");
return response;
}
LOGGER.debug("Getting binary security token from validate target");
BinarySecurityTokenType binarySecurityToken = (BinarySecurityTokenType) validateTarget.getToken();
//
// Decode the token
//
LOGGER.debug("Decoding binary security token.");
String base64Token = binarySecurityToken.getValue();
String ticket = null;
String service = null;
try {
byte[] token = Base64.getDecoder().decode(base64Token);
if (token == null || token.length == 0) {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null.");
}
String decodedToken = new String(token, Charset.forName("UTF-8"));
if (StringUtils.isNotBlank(decodedToken)) {
LOGGER.debug("Binary security token successfully decoded: {}", decodedToken);
// Token is in the format ticket|service
String[] parts = StringUtils.split(decodedToken, CAS_BST_SEP);
if (parts.length == 2) {
ticket = parts[0];
service = parts[1];
} else {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Was not able to parse out BST propertly. Should be in ticket|service format.");
}
} else {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null.");
}
} catch (WSSecurityException wsse) {
String msg = "Unable to decode BST into ticket and service for validation to CAS.";
LOGGER.info(msg, wsse);
return response;
}
//
try {
LOGGER.debug("Validating ticket [{}] for service [{}].", ticket, service);
// validate either returns an assertion or throws an exception
Assertion assertion = validate(ticket, service);
AttributePrincipal principal = assertion.getPrincipal();
LOGGER.debug("User name retrieved from CAS: {}", principal.getName());
response.setPrincipal(principal);
LOGGER.debug("CAS ticket successfully validated, setting state to valid.");
validateTarget.setState(STATE.VALID);
} catch (TicketValidationException e) {
LOGGER.debug("Unable to validate CAS token.", e);
}
return response;
}
use of org.apache.cxf.sts.request.ReceivedToken in project ddf by codice.
the class TestUsernameTokenValidator method testValidateGoodToken.
@Test
public void testValidateGoodToken() {
UsernameTokenValidator usernameTokenValidator = getUsernameTokenValidator(new XmlParser(), niceValidator);
usernameTokenValidator.addRealm(null);
TokenValidatorParameters tokenValidatorParameters = mock(TokenValidatorParameters.class);
STSPropertiesMBean stsPropertiesMBean = mock(STSPropertiesMBean.class);
when(stsPropertiesMBean.getSignatureCrypto()).thenReturn(mock(Crypto.class));
when(tokenValidatorParameters.getStsProperties()).thenReturn(stsPropertiesMBean);
ReceivedToken receivedToken = mock(ReceivedToken.class);
doCallRealMethod().when(receivedToken).setState(any(ReceivedToken.STATE.class));
doCallRealMethod().when(receivedToken).getState();
when(receivedToken.isUsernameToken()).thenReturn(true);
when(tokenValidatorParameters.getToken()).thenReturn(receivedToken);
Set<Class<?>> classes = new HashSet<>();
classes.add(ObjectFactory.class);
classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
JAXBContextCache.CachedContextAndSchemas cache = null;
try {
cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
} catch (JAXBException e) {
fail(e.getMessage());
}
JAXBContext jaxbContext = cache.getContext();
Unmarshaller unmarshaller = null;
try {
if (jaxbContext != null) {
unmarshaller = jaxbContext.createUnmarshaller();
}
} catch (JAXBException e) {
fail(e.getMessage());
}
JAXBElement<?> token = null;
if (unmarshaller != null) {
try {
token = (JAXBElement<?>) unmarshaller.unmarshal(this.getClass().getResourceAsStream("/user.xml"));
} catch (JAXBException e) {
fail(e.getMessage());
}
}
when(receivedToken.getToken()).thenReturn(token.getValue());
TokenValidatorResponse tokenValidatorResponse = usernameTokenValidator.validateToken(tokenValidatorParameters);
assertEquals(ReceivedToken.STATE.VALID, tokenValidatorResponse.getToken().getState());
verify(failedLoginDelayer, never()).delay(anyString());
}
use of org.apache.cxf.sts.request.ReceivedToken in project ddf by codice.
the class TestUsernameTokenValidator method testNoParser.
@Test(expected = IllegalStateException.class)
public void testNoParser() {
UsernameTokenValidator usernameTokenValidator = getUsernameTokenValidator(null, meanValidator);
usernameTokenValidator.addRealm(null);
TokenValidatorParameters tokenValidatorParameters = mock(TokenValidatorParameters.class);
STSPropertiesMBean stsPropertiesMBean = mock(STSPropertiesMBean.class);
when(stsPropertiesMBean.getSignatureCrypto()).thenReturn(mock(Crypto.class));
when(tokenValidatorParameters.getStsProperties()).thenReturn(stsPropertiesMBean);
ReceivedToken receivedToken = mock(ReceivedToken.class);
doCallRealMethod().when(receivedToken).setState(any(ReceivedToken.STATE.class));
doCallRealMethod().when(receivedToken).getState();
when(receivedToken.isUsernameToken()).thenReturn(true);
when(tokenValidatorParameters.getToken()).thenReturn(receivedToken);
Set<Class<?>> classes = new HashSet<>();
classes.add(ObjectFactory.class);
classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
JAXBContextCache.CachedContextAndSchemas cache = null;
try {
cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
} catch (JAXBException e) {
fail(e.getMessage());
}
JAXBContext jaxbContext = cache.getContext();
Unmarshaller unmarshaller = null;
try {
if (jaxbContext != null) {
unmarshaller = jaxbContext.createUnmarshaller();
}
} catch (JAXBException e) {
fail(e.getMessage());
}
JAXBElement<?> token = null;
if (unmarshaller != null) {
try {
token = (JAXBElement<?>) unmarshaller.unmarshal(this.getClass().getResourceAsStream("/user-no-password.xml"));
} catch (JAXBException e) {
fail(e.getMessage());
}
}
when(receivedToken.getToken()).thenReturn(token.getValue());
usernameTokenValidator.validateToken(tokenValidatorParameters);
}
use of org.apache.cxf.sts.request.ReceivedToken in project ddf by codice.
the class X509PathTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*
* @param tokenParameters
* @return TokenValidatorResponse
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.trace("Validating X.509 Token");
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
Crypto sigCrypto = stsProperties.getSignatureCrypto();
CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(sigCrypto);
requestData.setWssConfig(WSSConfig.getNewInstance());
requestData.setCallbackHandler(callbackHandler);
requestData.setMsgContext(tokenParameters.getMessageContext());
requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
BinarySecurity binarySecurity = null;
BinarySecurityTokenType binarySecurityType = null;
if (validateTarget.isBinarySecurityToken()) {
binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
// Test the encoding type
String encodingType = binarySecurityType.getEncodingType();
if (!BASE64_ENCODING.equals(encodingType)) {
LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
return response;
}
//
// Turn the received JAXB object into a DOM element
//
Document doc = DOMUtils.createDocument();
binarySecurity = new X509Security(doc);
binarySecurity.setEncodingType(encodingType);
binarySecurity.setValueType(binarySecurityType.getValueType());
String data = binarySecurityType.getValue();
Node textNode = doc.createTextNode(data);
binarySecurity.getElement().appendChild(textNode);
} else if (validateTarget.isDOMElement()) {
try {
Document doc = DOMUtils.createDocument();
binarySecurity = new X509Security(doc);
binarySecurity.setEncodingType(BASE64_ENCODING);
X509Data x509Data = new X509Data((Element) validateTarget.getToken(), "");
if (x509Data.containsCertificate()) {
XMLX509Certificate xmlx509Certificate = x509Data.itemCertificate(0);
if (xmlx509Certificate == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN);
}
X509Certificate cert = xmlx509Certificate.getX509Certificate();
((X509Security) binarySecurity).setX509Certificate(cert);
}
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to set certificate", ex);
return response;
} catch (XMLSecurityException ex) {
LOGGER.debug("Unable to get certificates", ex);
return response;
}
} else {
return response;
}
//
try {
Credential credential = new Credential();
credential.setBinarySecurityToken(binarySecurity);
if (merlin != null) {
byte[] token = binarySecurity.getToken();
if (token != null) {
if (binarySecurityType != null) {
if (binarySecurityType.getValueType().equals(X509_PKI_PATH)) {
X509Certificate[] certificates = merlin.getCertificatesFromBytes(token);
if (certificates != null) {
credential.setCertificates(certificates);
}
} else {
X509Certificate singleCert = merlin.loadCertificate(new ByteArrayInputStream(token));
credential.setCertificates(new X509Certificate[] { singleCert });
}
}
} else {
LOGGER.debug("Binary Security Token bytes were null.");
}
}
Credential returnedCredential = validator.validate(credential, requestData);
X500Principal subjectX500Principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
response.setPrincipal(subjectX500Principal);
if (response.getAdditionalProperties() == null) {
response.setAdditionalProperties(new HashMap<>());
}
try {
String emailAddress = SubjectUtils.getEmailAddress(subjectX500Principal);
if (emailAddress != null) {
response.getAdditionalProperties().put(SubjectUtils.EMAIL_ADDRESS_CLAIM_URI, emailAddress);
}
String country = SubjectUtils.getCountry(subjectX500Principal);
if (country != null) {
response.getAdditionalProperties().put(SubjectUtils.COUNTRY_CLAIM_URI, country);
}
} catch (Exception e) {
LOGGER.debug("Unable to set email address or country from certificate.", e);
}
validateTarget.setState(STATE.VALID);
validateTarget.setPrincipal(subjectX500Principal);
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to validate credentials.", ex);
}
return response;
}
Aggregations