use of org.codice.ddf.security.handler.api.UPAuthenticationToken in project ddf by codice.
the class BasicAuthenticationHandlerTest method testIllegalStateException.
@Test(expected = IllegalStateException.class)
public void testIllegalStateException() {
BasicAuthenticationHandler handler = new BasicAuthenticationHandler();
UPAuthenticationToken result = (UPAuthenticationToken) handler.extractAuthInfo("Basic " + Base64.getEncoder().encodeToString(CREDENTIALS.getBytes()), "TestRealm");
assertNotNull(result);
assertEquals("admin", result.getUsername());
assertEquals("password", result.getPassword());
assertEquals("TestRealm", result.getRealm());
WssBasicAuthenticationHandler wssHandler = new WssBasicAuthenticationHandler(null);
BaseAuthenticationToken wssResult = wssHandler.extractAuthInfo("Basic " + Base64.getEncoder().encodeToString(CREDENTIALS.getBytes()), "TestRealm");
}
use of org.codice.ddf.security.handler.api.UPAuthenticationToken in project ddf by codice.
the class IdpEndpoint method handleLogin.
protected org.opensaml.saml.saml2.core.Response handleLogin(AuthnRequest authnRequest, String authMethod, HttpServletRequest request, AuthObj authObj, boolean passive, boolean hasCookie) throws SecurityServiceException, WSSecurityException, SimpleSign.SignatureException, ConstraintViolationException {
LOGGER.debug("Performing login for user. passive: {}, cookie: {}", passive, hasCookie);
BaseAuthenticationToken token = null;
request.setAttribute(ContextPolicy.ACTIVE_REALM, BaseAuthenticationToken.ALL_REALM);
if (PKI.equals(authMethod)) {
LOGGER.debug("Logging user in via PKI.");
PKIHandler pkiHandler = new PKIHandler();
pkiHandler.setTokenFactory(tokenFactory);
try {
HandlerResult handlerResult = pkiHandler.getNormalizedToken(request, null, null, false);
if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
token = handlerResult.getToken();
}
} catch (ServletException e) {
LOGGER.info("Encountered an exception while checking for PKI auth info.", e);
}
} else if (USER_PASS.equals(authMethod)) {
LOGGER.debug("Logging user in via BASIC auth.");
if (authObj != null && authObj.username != null && authObj.password != null) {
token = new UPAuthenticationToken(authObj.username, authObj.password, BaseAuthenticationToken.ALL_REALM);
} else {
BasicAuthenticationHandler basicAuthenticationHandler = new BasicAuthenticationHandler();
HandlerResult handlerResult = basicAuthenticationHandler.getNormalizedToken(request, null, null, false);
if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
token = handlerResult.getToken();
}
}
} else if (SAML.equals(authMethod)) {
LOGGER.debug("Logging user in via SAML assertion.");
token = new SAMLAuthenticationToken(null, authObj.assertion, BaseAuthenticationToken.ALL_REALM);
} else if (GUEST.equals(authMethod) && guestAccess) {
LOGGER.debug("Logging user in as Guest.");
token = new GuestAuthenticationToken(BaseAuthenticationToken.ALL_REALM, request.getRemoteAddr());
} else {
throw new IllegalArgumentException("Auth method is not supported.");
}
org.w3c.dom.Element samlToken = null;
String statusCode;
if (hasCookie) {
samlToken = getSamlAssertion(request);
statusCode = StatusCode.SUCCESS;
} else {
try {
statusCode = StatusCode.AUTHN_FAILED;
Subject subject = securityManager.getSubject(token);
for (Object principal : subject.getPrincipals().asList()) {
if (principal instanceof SecurityAssertion) {
SecurityToken securityToken = ((SecurityAssertion) principal).getSecurityToken();
samlToken = securityToken.getToken();
}
}
if (samlToken != null) {
statusCode = StatusCode.SUCCESS;
}
} catch (SecurityServiceException e) {
if (!passive) {
throw e;
} else {
statusCode = StatusCode.AUTHN_FAILED;
}
}
}
LOGGER.debug("User log in successful.");
return SamlProtocol.createResponse(SamlProtocol.createIssuer(SystemBaseUrl.constructUrl("/idp/login", true)), SamlProtocol.createStatus(statusCode), authnRequest.getID(), samlToken);
}
use of org.codice.ddf.security.handler.api.UPAuthenticationToken in project ddf by codice.
the class UPBSTValidator method canHandleToken.
/**
* Return true if this TokenValidator implementation is capable of validating the
* ReceivedToken argument. The realm is ignored in this token Validator.
*
* @param validateTarget
* @param cxfRealm
* @return true if the token can be handled
*/
public boolean canHandleToken(ReceivedToken validateTarget, String cxfRealm) {
boolean canHandle = false;
UPAuthenticationToken usernameToken = getUsernameTokenFromTarget(validateTarget);
if (usernameToken != null) {
// This generic instance just looks for the default realms (DDF and Karaf)
if (usernameToken.getRealm() == null) {
LOGGER.trace("No realm specified in request");
canHandle = (validators != null);
} else if (validators != null && validators.containsKey(usernameToken.getRealm())) {
LOGGER.trace("Realm '{}' recognized - canHandleToken = true", usernameToken.getRealm());
canHandle = true;
} else if (validators != null && "*".equals(usernameToken.getRealm())) {
LOGGER.trace("Realm '*' recognized - canHandleToken = true");
canHandle = true;
}
if (!canHandle) {
LOGGER.trace("Realm '{}' unrecognized - canHandleToken = false", usernameToken.getRealm());
}
}
LOGGER.debug("Returning canHandle: {}", canHandle);
return canHandle;
}
use of org.codice.ddf.security.handler.api.UPAuthenticationToken in project ddf by codice.
the class UPBSTValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*
* @param tokenParameters
* @return TokenValidatorResponse
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.trace("Validating UPBST Token");
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);
requestData.setWssConfig(WSSConfig.getNewInstance());
requestData.setCallbackHandler(callbackHandler);
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
if (!validateTarget.isBinarySecurityToken()) {
return response;
}
BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
// Test the encoding type
String encodingType = binarySecurityType.getEncodingType();
if (!UPAuthenticationToken.BASE64_ENCODING.equals(encodingType)) {
LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
return response;
}
UPAuthenticationToken usernameToken = getUsernameTokenFromTarget(validateTarget);
if (usernameToken == null) {
return response;
}
UsernameTokenType usernameTokenType = getUsernameTokenType(usernameToken);
// Marshall the received JAXB object into a DOM Element
Element usernameTokenElement = null;
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());
ParserConfigurator configurator = parser.configureParser(ctxPath, UPBSTValidator.class.getClassLoader());
try {
parser.marshal(configurator, tokenType, rootElement);
} catch (ParserException ex) {
LOGGER.info("Unable to parse username token", ex);
return response;
}
usernameTokenElement = (Element) rootElement.getFirstChild();
//
// Validate the token
//
WSSConfig wssConfig = WSSConfig.getNewInstance();
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;
}
String tokenId = String.format("%s:%s:%s", usernameToken.getUsername(), usernameToken.getPassword(), usernameToken.getRealm());
// See if the UsernameToken is stored in the cache
int hash = tokenId.hashCode();
SecurityToken secToken = null;
if (tokenParameters.getTokenStore() != null) {
secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
if (secToken != null && secToken.getTokenHash() != hash) {
secToken = null;
} else if (secToken != null) {
validateTarget.setState(STATE.VALID);
}
}
if (secToken == null) {
Credential credential = new Credential();
credential.setUsernametoken(ut);
if (usernameToken.getRealm() != null && !"*".equals(usernameToken.getRealm())) {
Validator validator = validators.get(usernameToken.getRealm());
if (validator != null) {
try {
validator.validate(credential, requestData);
validateTarget.setState(STATE.VALID);
LOGGER.debug("Validated user against realm {}", usernameToken.getRealm());
} catch (WSSecurityException ex) {
LOGGER.debug("Not able to validate user against realm {}", usernameToken.getRealm());
}
}
} else {
Set<Map.Entry<String, Validator>> entries = validators.entrySet();
for (Map.Entry<String, Validator> entry : entries) {
try {
entry.getValue().validate(credential, requestData);
validateTarget.setState(STATE.VALID);
LOGGER.debug("Validated user against realm {}", entry.getKey());
break;
} catch (WSSecurityException ex) {
LOGGER.debug("Not able to validate user against realm {}", entry.getKey());
}
}
}
}
Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
// Store the successfully validated token in the cache
if (tokenParameters.getTokenStore() != null && secToken == null && STATE.VALID.equals(validateTarget.getState())) {
secToken = new SecurityToken(ut.getID());
secToken.setToken(ut.getElement());
int hashCode = tokenId.hashCode();
String identifier = Integer.toString(hashCode);
secToken.setTokenHash(hashCode);
tokenParameters.getTokenStore().add(identifier, secToken);
}
response.setPrincipal(principal);
response.setTokenRealm(null);
validateTarget.setPrincipal(principal);
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to validate token.", ex);
}
if (response.getToken().getState() != STATE.VALID) {
failedLoginDelayer.delay(response.getToken().getPrincipal().getName());
}
return response;
}
use of org.codice.ddf.security.handler.api.UPAuthenticationToken in project ddf by codice.
the class Security method getSubject.
/**
* Gets the {@link Subject} given a user name and password.
*
* @param username username
* @param password password
* @return {@link Subject} associated with the user name and password provided
*/
public Subject getSubject(String username, String password) {
UPAuthenticationToken token = new UPAuthenticationToken(username, password);
SecurityManager securityManager = getSecurityManager();
if (securityManager != null) {
try {
return securityManager.getSubject(token);
} catch (SecurityServiceException | RuntimeException e) {
LOGGER.info("Unable to request subject for {} user.", username, e);
}
}
return null;
}
Aggregations