use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.
the class SAMLAssertionHandlerTest method testGetNormalizedTokenSuccessWithHeader.
/**
* This test ensures the proper functionality of SAMLAssertionHandler's
* method, getNormalizedToken(), when given a valid HttpServletRequest.
*/
@Test
public void testGetNormalizedTokenSuccessWithHeader() throws Exception {
SAMLAssertionHandler handler = new SAMLAssertionHandler();
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
Element assertion = readDocument("/saml.xml").getDocumentElement();
String assertionId = assertion.getAttributeNodeNS(null, "ID").getNodeValue();
SecurityToken samlToken = new SecurityToken(assertionId, assertion, null);
SamlAssertionWrapper wrappedAssertion = new SamlAssertionWrapper(samlToken.getToken());
String saml = wrappedAssertion.assertionToString();
doReturn("SAML " + RestSecurity.deflateAndBase64Encode(saml)).when(request).getHeader(SecurityConstants.SAML_HEADER_NAME);
HandlerResult result = handler.getNormalizedToken(request, response, chain, true);
assertNotNull(result);
assertEquals(HandlerResult.Status.COMPLETED, result.getStatus());
}
use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.
the class SAMLAssertionHandlerTest method testGetNormalizedTokenSuccessWithCookie.
/**
* This test ensures the proper functionality of SAMLAssertionHandler's
* method, getNormalizedToken(), when given a valid HttpServletRequest.
* Uses legacy SAML cookie
*/
@Test
public void testGetNormalizedTokenSuccessWithCookie() throws Exception {
SAMLAssertionHandler handler = new SAMLAssertionHandler();
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
Element assertion = readDocument("/saml.xml").getDocumentElement();
String assertionId = assertion.getAttributeNodeNS(null, "ID").getNodeValue();
SecurityToken samlToken = new SecurityToken(assertionId, assertion, null);
SamlAssertionWrapper wrappedAssertion = new SamlAssertionWrapper(samlToken.getToken());
String saml = wrappedAssertion.assertionToString();
Cookie cookie = new Cookie(SecurityConstants.SAML_COOKIE_NAME, RestSecurity.deflateAndBase64Encode(saml));
when(request.getCookies()).thenReturn(new Cookie[] { cookie });
HandlerResult result = handler.getNormalizedToken(request, response, chain, true);
assertNotNull(result);
assertEquals(HandlerResult.Status.COMPLETED, result.getStatus());
}
use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.
the class SecurityAssertionStore method getSecurityAssertion.
/**
* Return the SecurityAssertion wrapper associated with the provided message
*
* @param message Message
* @return SecurityAssertion
*/
public static SecurityAssertion getSecurityAssertion(Message message) {
if (message != null) {
TokenStore tokenStore = getTokenStore(message);
Principal principal = null;
SecurityContext context = message.get(SecurityContext.class);
if (context != null) {
principal = context.getUserPrincipal();
}
if (!(principal instanceof SAMLTokenPrincipal)) {
// Try to find the SAMLTokenPrincipal if it exists
List<?> wsResults = List.class.cast(message.get(WSHandlerConstants.RECV_RESULTS));
if (wsResults != null) {
for (Object wsResult : wsResults) {
if (wsResult instanceof WSHandlerResult) {
List<WSSecurityEngineResult> wsseResults = ((WSHandlerResult) wsResult).getResults();
for (WSSecurityEngineResult wsseResult : wsseResults) {
Object principalResult = wsseResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
if (principalResult instanceof SAMLTokenPrincipal) {
principal = (SAMLTokenPrincipal) principalResult;
break;
}
}
}
}
}
}
if (tokenStore != null && principal != null && principal instanceof SAMLTokenPrincipal) {
String id = ((SAMLTokenPrincipal) principal).getId();
SamlAssertionWrapper samlAssertionWrapper = ((SAMLTokenPrincipal) principal).getToken();
SecurityToken token = tokenStore.getToken(id);
if (token == null) {
if (samlAssertionWrapper.getSaml2().getIssueInstant() != null && samlAssertionWrapper.getSaml2().getConditions() != null && samlAssertionWrapper.getSaml2().getConditions().getNotOnOrAfter() != null) {
token = new SecurityToken(id, samlAssertionWrapper.getElement(), samlAssertionWrapper.getSaml2().getIssueInstant().toDate(), samlAssertionWrapper.getSaml2().getConditions().getNotOnOrAfter().toDate());
} else {
// we don't know how long this should last or when it was created, so just
// set it to 1 minute
// This shouldn't happen unless someone sets up a third party STS with weird
// settings.
Date date = new Date();
token = new SecurityToken(id, samlAssertionWrapper.getElement(), date, new Date(date.getTime() + TimeUnit.MINUTES.toMillis(1)));
}
tokenStore.add(token);
}
return new SecurityAssertionImpl(token);
}
}
return new SecurityAssertionImpl();
}
use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.
the class LoginFilter method handleAuthenticationToken.
private Subject handleAuthenticationToken(HttpServletRequest httpRequest, SAMLAuthenticationToken token) throws ServletException {
Subject subject;
try {
LOGGER.debug("Validating received SAML assertion.");
boolean wasReference = false;
boolean firstLogin = true;
if (token.isReference()) {
wasReference = true;
LOGGER.trace("Converting SAML reference to assertion");
Object sessionToken = httpRequest.getSession(false).getAttribute(SecurityConstants.SAML_ASSERTION);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Http Session assertion - class: {} loader: {}", sessionToken.getClass().getName(), sessionToken.getClass().getClassLoader());
LOGGER.trace("SecurityToken class: {} loader: {}", SecurityToken.class.getName(), SecurityToken.class.getClassLoader());
}
SecurityToken savedToken = null;
try {
savedToken = ((SecurityTokenHolder) sessionToken).getSecurityToken(token.getRealm());
} catch (ClassCastException e) {
httpRequest.getSession(false).invalidate();
}
if (savedToken != null) {
firstLogin = false;
token.replaceReferenece(savedToken);
}
if (token.isReference()) {
String msg = "Missing or invalid SAML assertion for provided reference.";
LOGGER.debug(msg);
throw new InvalidSAMLReceivedException(msg);
}
}
SAMLAuthenticationToken newToken = renewSecurityToken(httpRequest.getSession(false), token);
SecurityToken securityToken;
if (newToken != null) {
firstLogin = false;
securityToken = (SecurityToken) newToken.getCredentials();
} else {
securityToken = (SecurityToken) token.getCredentials();
}
if (!wasReference) {
// wrap the token
SamlAssertionWrapper assertion = new SamlAssertionWrapper(securityToken.getToken());
// get the crypto junk
Crypto crypto = getSignatureCrypto();
Response samlResponse = createSamlResponse(httpRequest.getRequestURI(), assertion.getIssuerString(), createStatus(SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null));
BUILDER.get().reset();
Document doc = BUILDER.get().newDocument();
Element policyElement = OpenSAMLUtil.toDom(samlResponse, doc);
doc.appendChild(policyElement);
Credential credential = new Credential();
credential.setSamlAssertion(assertion);
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(crypto);
WSSConfig wssConfig = WSSConfig.getNewInstance();
requestData.setWssConfig(wssConfig);
X509Certificate[] x509Certs = (X509Certificate[]) httpRequest.getAttribute("javax.servlet.request.X509Certificate");
requestData.setTlsCerts(x509Certs);
validateHolderOfKeyConfirmation(assertion, x509Certs);
if (assertion.isSigned()) {
// Verify the signature
WSSSAMLKeyInfoProcessor wsssamlKeyInfoProcessor = new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument()));
assertion.verifySignature(wsssamlKeyInfoProcessor, crypto);
assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument())), requestData.getSigVerCrypto(), requestData.getCallbackHandler());
}
// Validate the Assertion & verify trust in the signature
assertionValidator.validate(credential, requestData);
}
// if it is all good, then we'll create our subject
subject = securityManager.getSubject(securityToken);
if (firstLogin) {
boolean hasSecurityAuditRole = Arrays.stream(System.getProperty("security.audit.roles").split(",")).filter(subject::hasRole).findFirst().isPresent();
if (hasSecurityAuditRole) {
SecurityLogger.audit("Subject has logged in with admin privileges", subject);
}
}
if (!wasReference && firstLogin) {
addSamlToSession(httpRequest, token.getRealm(), securityToken);
}
} catch (SecurityServiceException e) {
LOGGER.debug("Unable to get subject from SAML request.", e);
throw new ServletException(e);
} catch (WSSecurityException e) {
LOGGER.debug("Unable to read/validate security token from request.", e);
throw new ServletException(e);
}
return subject;
}
use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project ddf by codice.
the class SamlProtocol method createResponse.
public static Response createResponse(Issuer issuer, Status status, String requestId, Element samlAssertion) throws WSSecurityException {
Response response = responseSAMLObjectBuilder.buildObject();
response.setIssuer(issuer);
response.setStatus(status);
response.setID("_" + UUID.randomUUID().toString());
response.setIssueInstant(new DateTime());
response.setInResponseTo(requestId);
response.setVersion(SAMLVersion.VERSION_20);
if (samlAssertion != null) {
SamlAssertionWrapper samlAssertionWrapper = new SamlAssertionWrapper(samlAssertion);
response.getAssertions().add(samlAssertionWrapper.getSaml2());
}
return response;
}
Aggregations