use of org.apache.wss4j.dom.message.token.UsernameToken in project cxf by apache.
the class STSLoginModule method login.
@Override
public boolean login() throws LoginException {
// Get username and password
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("Username: ");
callbacks[1] = new PasswordCallback("Password: ", false);
try {
callbackHandler.handle(callbacks);
} catch (IOException ioException) {
throw new LoginException(ioException.getMessage());
} catch (UnsupportedCallbackException unsupportedCallbackException) {
throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
}
String user = ((NameCallback) callbacks[0]).getName();
char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
if (tmpPassword == null) {
tmpPassword = new char[0];
}
String password = new String(tmpPassword);
roles = new HashSet<>();
userPrincipal = null;
STSTokenValidator validator = new STSTokenValidator(true);
validator.setUseIssueBinding(requireRoles);
validator.setUseOnBehalfOf(!disableOnBehalfOf);
validator.setDisableCaching(!requireRoles || disableCaching);
// Authenticate token
try {
UsernameToken token = convertToToken(user, password);
Credential credential = new Credential();
credential.setUsernametoken(token);
RequestData data = new RequestData();
Message message = PhaseInterceptorChain.getCurrentMessage();
STSClient stsClient = configureSTSClient(message);
if (message != null) {
message.put(SecurityConstants.STS_CLIENT, stsClient);
data.setMsgContext(message);
} else {
validator.setStsClient(stsClient);
}
credential = validator.validate(credential, data);
// Add user principal
userPrincipal = new SimplePrincipal(user);
// Add roles if a SAML Assertion was returned from the STS
roles.addAll(getRoles(message, credential));
} catch (Exception e) {
LOG.log(Level.INFO, "User " + user + " authentication failed", e);
throw new LoginException("User " + user + " authentication failed: " + e.getMessage());
}
succeeded = true;
return true;
}
use of org.apache.wss4j.dom.message.token.UsernameToken in project cxf by apache.
the class WSS4JBasicAuthValidator method convertPolicyToToken.
protected UsernameToken convertPolicyToToken(AuthorizationPolicy policy) {
Document doc = DOMUtils.getEmptyDocument();
UsernameToken token = new UsernameToken(false, doc, WSS4JConstants.PASSWORD_TEXT);
token.setName(policy.getUserName());
token.setPassword(policy.getPassword());
return token;
}
use of org.apache.wss4j.dom.message.token.UsernameToken in project cxf by apache.
the class WSS4JBasicAuthValidator method validate.
protected void validate(Message message) throws WSSecurityException {
AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
String name = null;
if (policy != null) {
name = policy.getUserName();
}
String errorMsg = "No user name and/or password is available, name: " + name;
LOG.warning(errorMsg);
throw new SecurityException(errorMsg);
}
UsernameToken token = convertPolicyToToken(policy);
Credential credential = new Credential();
credential.setUsernametoken(token);
RequestData data = new RequestData();
data.setMsgContext(message);
data.setCallbackHandler(callbackHandler);
credential = getValidator().validate(credential, data);
// Create a Principal/SecurityContext
final SecurityContext sc;
if (credential != null && credential.getPrincipal() != null) {
sc = createSecurityContext(message, credential);
} else {
Principal p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
((WSUsernameTokenPrincipalImpl) p).setPassword(policy.getPassword());
sc = createSecurityContext(p);
}
message.put(SecurityContext.class, sc);
}
use of org.apache.wss4j.dom.message.token.UsernameToken in project cxf by apache.
the class UsernameTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOG.fine("Validating UsernameToken");
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);
requestData.setMsgContext(tokenParameters.getMessageContext());
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(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();
// Marshall the received JAXB object into a DOM Element
final Element usernameTokenElement;
try {
Set<Class<?>> classes = new HashSet<>();
classes.add(ObjectFactory.class);
classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
CachedContextAndSchemas cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
JAXBContext jaxbContext = cache.getContext();
Marshaller marshaller = jaxbContext.createMarshaller();
Document doc = DOMUtils.getEmptyDocument();
Element rootElement = doc.createElement("root-element");
JAXBElement<UsernameTokenType> tokenType = new JAXBElement<UsernameTokenType>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
marshaller.marshal(tokenType, rootElement);
usernameTokenElement = (Element) rootElement.getFirstChild();
} catch (JAXBException ex) {
LOG.log(Level.WARNING, "", 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) {
return response;
}
// See if the UsernameToken is stored in the cache
int hash = ut.hashCode();
SecurityToken secToken = null;
if (tokenParameters.getTokenStore() != null) {
secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
if (secToken != null && (secToken.getTokenHash() != hash || secToken.isExpired())) {
secToken = null;
}
}
Principal principal = null;
if (secToken == null) {
Credential credential = new Credential();
credential.setUsernametoken(ut);
credential = validator.validate(credential, requestData);
principal = credential.getPrincipal();
if (credential.getSubject() != null && roleParser != null) {
// Parse roles from the validated token
Set<Principal> roles = roleParser.parseRolesFromSubject(principal, credential.getSubject());
response.setRoles(roles);
}
}
if (principal == null) {
principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
}
// Get the realm of the UsernameToken
String tokenRealm = null;
if (usernameTokenRealmCodec != null) {
tokenRealm = usernameTokenRealmCodec.getRealmFromToken(ut);
// verify the realm against the cached token
if (secToken != null) {
Map<String, Object> props = secToken.getProperties();
if (props != null) {
String cachedRealm = (String) props.get(STSConstants.TOKEN_REALM);
if (!tokenRealm.equals(cachedRealm)) {
return response;
}
}
}
}
// Store the successfully validated token in the cache
if (tokenParameters.getTokenStore() != null && secToken == null) {
secToken = new SecurityToken(ut.getID());
secToken.setToken(ut.getElement());
int hashCode = ut.hashCode();
String identifier = Integer.toString(hashCode);
secToken.setTokenHash(hashCode);
tokenParameters.getTokenStore().add(identifier, secToken);
}
response.setPrincipal(principal);
response.setTokenRealm(tokenRealm);
validateTarget.setState(STATE.VALID);
LOG.fine("Username Token successfully validated");
} catch (WSSecurityException ex) {
LOG.log(Level.WARNING, "", ex);
}
return response;
}
use of org.apache.wss4j.dom.message.token.UsernameToken in project cxf by apache.
the class UsernameTokenValidatorTest method testValidUsernameTokenDigest.
/**
* Test a valid UsernameToken with password digest
*/
@org.junit.Test
public void testValidUsernameTokenDigest() throws Exception {
TokenValidator usernameTokenValidator = new UsernameTokenValidator();
TokenValidatorParameters validatorParameters = createValidatorParameters();
TokenRequirements tokenRequirements = validatorParameters.getTokenRequirements();
// Create a ValidateTarget consisting of a UsernameToken
UsernameTokenType usernameToken = new UsernameTokenType();
AttributedString username = new AttributedString();
username.setValue("alice");
usernameToken.setUsername(username);
JAXBElement<UsernameTokenType> tokenType = new JAXBElement<UsernameTokenType>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameToken);
// Create a WSS4J UsernameToken
Document doc = DOMUtils.createDocument();
UsernameToken ut = new UsernameToken(true, doc, WSS4JConstants.PASSWORD_DIGEST);
ut.setName("alice");
ut.setPassword("clarinet");
ut.addNonce(doc);
ut.addCreated(true, doc);
// Add a password
PasswordString password = new PasswordString();
password.setValue(ut.getPassword());
password.setType(WSS4JConstants.PASSWORD_DIGEST);
JAXBElement<PasswordString> passwordType = new JAXBElement<PasswordString>(QNameConstants.PASSWORD, PasswordString.class, password);
usernameToken.getAny().add(passwordType);
// Add a nonce
EncodedString nonce = new EncodedString();
nonce.setValue(ut.getNonce());
nonce.setEncodingType(WSS4JConstants.SOAPMESSAGE_NS + "#Base64Binary");
JAXBElement<EncodedString> nonceType = new JAXBElement<EncodedString>(QNameConstants.NONCE, EncodedString.class, nonce);
usernameToken.getAny().add(nonceType);
// Add Created value
String created = ut.getCreated();
Element createdElement = doc.createElementNS(WSS4JConstants.WSU_NS, "Created");
createdElement.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns", WSS4JConstants.WSU_NS);
createdElement.setTextContent(created);
usernameToken.getAny().add(createdElement);
ReceivedToken validateTarget = new ReceivedToken(tokenType);
tokenRequirements.setValidateTarget(validateTarget);
validatorParameters.setToken(validateTarget);
assertTrue(usernameTokenValidator.canHandleToken(validateTarget));
TokenValidatorResponse validatorResponse = usernameTokenValidator.validateToken(validatorParameters);
assertNotNull(validatorResponse);
assertNotNull(validatorResponse.getToken());
assertTrue(validatorResponse.getToken().getState() == STATE.VALID);
Principal principal = validatorResponse.getPrincipal();
assertTrue(principal != null && principal.getName() != null);
// Expected failure on a bad password
password.setValue("badpassword");
validatorResponse = usernameTokenValidator.validateToken(validatorParameters);
assertNotNull(validatorResponse);
assertNotNull(validatorResponse.getToken());
assertTrue(validatorResponse.getToken().getState() == STATE.INVALID);
}
Aggregations