use of org.apache.cxf.sts.STSPropertiesMBean in project ddf by codice.
the class UsernameTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.debug("Validating UsernameToken");
if (parser == null) {
throw new IllegalStateException("XMLParser must be configured.");
}
if (failedLoginDelayer == null) {
throw new IllegalStateException("Failed Login Delayer must be configured");
}
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);
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(ReceivedToken.STATE.INVALID);
response.setToken(validateTarget);
if (!validateTarget.isUsernameToken()) {
return response;
}
//
// Turn the JAXB UsernameTokenType into a DOM Element for validation
//
UsernameTokenType usernameTokenType = (UsernameTokenType) validateTarget.getToken();
JAXBElement<UsernameTokenType> tokenType = new JAXBElement<>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
Document doc = DOMUtils.createDocument();
Element rootElement = doc.createElement("root-element");
List<String> ctxPath = new ArrayList<>(1);
ctxPath.add(UsernameTokenType.class.getPackage().getName());
Element usernameTokenElement = null;
ParserConfigurator configurator = parser.configureParser(ctxPath, UsernameTokenValidator.class.getClassLoader());
try {
parser.marshal(configurator, tokenType, rootElement);
usernameTokenElement = (Element) rootElement.getFirstChild();
} catch (ParserException ex) {
LOGGER.info("Unable to parse username token", ex);
return response;
}
//
try {
boolean allowNamespaceQualifiedPasswordTypes = requestData.isAllowNamespaceQualifiedPasswordTypes();
UsernameToken ut = new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, new BSPEnforcer());
// The parsed principal is set independent whether validation is successful or not
response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
if (ut.getPassword() == null) {
failedLoginDelayer.delay(ut.getName());
return response;
}
Credential credential = new Credential();
credential.setUsernametoken(ut);
//Only this section is new, the rest is copied from the apache class
Set<Map.Entry<String, Validator>> entries = validators.entrySet();
for (Map.Entry<String, Validator> entry : entries) {
try {
entry.getValue().validate(credential, requestData);
validateTarget.setState(ReceivedToken.STATE.VALID);
break;
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to validate user against {}" + entry.getKey(), ex);
}
}
if (ReceivedToken.STATE.INVALID.equals(validateTarget.getState())) {
failedLoginDelayer.delay(ut.getName());
return response;
}
//end new section
Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
response.setPrincipal(principal);
response.setTokenRealm(null);
validateTarget.setState(ReceivedToken.STATE.VALID);
validateTarget.setPrincipal(principal);
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to validate token.", ex);
}
return response;
}
use of org.apache.cxf.sts.STSPropertiesMBean in project ddf by codice.
the class TestUsernameTokenValidator method testValidateBadTokenNoTokenStore.
@Test
public void testValidateBadTokenNoTokenStore() {
UsernameTokenValidator usernameTokenValidator = getUsernameTokenValidator(new XmlParser(), 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());
TokenValidatorResponse tokenValidatorResponse = usernameTokenValidator.validateToken(tokenValidatorParameters);
assertEquals(ReceivedToken.STATE.INVALID, tokenValidatorResponse.getToken().getState());
verify(failedLoginDelayer, times(1)).delay(anyString());
}
use of org.apache.cxf.sts.STSPropertiesMBean in project ddf by codice.
the class TestUsernameTokenValidator method testValidateBadToken.
@Test
public void testValidateBadToken() {
UsernameTokenValidator usernameTokenValidator = getUsernameTokenValidator(new XmlParser(), 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.xml"));
} catch (JAXBException e) {
fail(e.getMessage());
}
}
when(receivedToken.getToken()).thenReturn(token.getValue());
TokenValidatorResponse tokenValidatorResponse = usernameTokenValidator.validateToken(tokenValidatorParameters);
assertEquals(ReceivedToken.STATE.INVALID, tokenValidatorResponse.getToken().getState());
verify(failedLoginDelayer, times(1)).delay(anyString());
}
use of org.apache.cxf.sts.STSPropertiesMBean in project ddf by codice.
the class TestUsernameTokenValidator method testNoFailedDelayer.
@Test(expected = IllegalStateException.class)
public void testNoFailedDelayer() {
UsernameTokenValidator usernameTokenValidator = new UsernameTokenValidator(new XmlParser(), null) {
public void addRealm(ServiceReference<JaasRealm> serviceReference) {
validators.put("myrealm", 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.STSPropertiesMBean in project cxf by apache.
the class DefaultSubjectProvider method createKeyInfo.
/**
* Create and return the KeyInfoBean to be inserted into the SubjectBean
*/
protected KeyInfoBean createKeyInfo(SubjectProviderParameters subjectProviderParameters) {
TokenProviderParameters providerParameters = subjectProviderParameters.getProviderParameters();
KeyRequirements keyRequirements = providerParameters.getKeyRequirements();
STSPropertiesMBean stsProperties = providerParameters.getStsProperties();
String keyType = keyRequirements.getKeyType();
if (STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyType)) {
Crypto crypto = stsProperties.getEncryptionCrypto();
EncryptionProperties encryptionProperties = providerParameters.getEncryptionProperties();
String encryptionName = encryptionProperties.getEncryptionName();
if (encryptionName == null) {
// Fall back on the STS encryption name
encryptionName = stsProperties.getEncryptionUsername();
}
if (encryptionName == null) {
LOG.fine("No encryption Name is configured for Symmetric KeyType");
throw new STSException("No Encryption Name is configured", STSException.REQUEST_FAILED);
}
CryptoType cryptoType = null;
// Check for using of service endpoint (AppliesTo) as certificate identifier
if (STSConstants.USE_ENDPOINT_AS_CERT_ALIAS.equals(encryptionName)) {
if (providerParameters.getAppliesToAddress() == null) {
throw new STSException("AppliesTo is not initilaized for encryption name " + STSConstants.USE_ENDPOINT_AS_CERT_ALIAS);
}
cryptoType = new CryptoType(CryptoType.TYPE.ENDPOINT);
cryptoType.setEndpoint(providerParameters.getAppliesToAddress());
} else {
cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
cryptoType.setAlias(encryptionName);
}
try {
X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
if ((certs == null) || (certs.length == 0)) {
throw new STSException("Encryption certificate is not found for alias: " + encryptionName);
}
Document doc = subjectProviderParameters.getDoc();
byte[] secret = subjectProviderParameters.getSecret();
return createEncryptedKeyKeyInfo(certs[0], secret, doc, encryptionProperties, crypto);
} catch (WSSecurityException ex) {
LOG.log(Level.WARNING, "", ex);
throw new STSException(ex.getMessage(), ex);
}
} else if (STSConstants.PUBLIC_KEY_KEYTYPE.equals(keyType)) {
ReceivedKey receivedKey = keyRequirements.getReceivedKey();
// Validate UseKey trust
if (stsProperties.isValidateUseKey() && stsProperties.getSignatureCrypto() != null) {
if (receivedKey.getX509Cert() != null) {
try {
Collection<Pattern> constraints = Collections.emptyList();
stsProperties.getSignatureCrypto().verifyTrust(new X509Certificate[] { receivedKey.getX509Cert() }, false, constraints, null);
} catch (WSSecurityException e) {
LOG.log(Level.FINE, "Error in trust validation of UseKey: ", e);
throw new STSException("Error in trust validation of UseKey", STSException.REQUEST_FAILED);
}
}
if (receivedKey.getPublicKey() != null) {
try {
stsProperties.getSignatureCrypto().verifyTrust(receivedKey.getPublicKey());
} catch (WSSecurityException e) {
LOG.log(Level.FINE, "Error in trust validation of UseKey: ", e);
throw new STSException("Error in trust validation of UseKey", STSException.REQUEST_FAILED);
}
}
}
return createPublicKeyKeyInfo(receivedKey.getX509Cert(), receivedKey.getPublicKey());
}
return null;
}
Aggregations