use of org.opensaml.saml.saml2.core.Response in project cloudstack by apache.
the class SAML2LogoutAPIAuthenticatorCmd method authenticate.
@Override
public String authenticate(String command, Map<String, Object[]> params, HttpSession session, InetAddress remoteAddress, String responseType, StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
auditTrailSb.append("=== SAML SLO Logging out ===");
LogoutCmdResponse response = new LogoutCmdResponse();
response.setDescription("success");
response.setResponseName(getCommandName());
String responseString = ApiResponseSerializer.toSerializedString(response, responseType);
if (session == null) {
try {
resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
} catch (IOException ignored) {
s_logger.info("[ignored] sending redirected failed.", ignored);
}
return responseString;
}
try {
DefaultBootstrap.bootstrap();
} catch (ConfigurationException | FactoryConfigurationError e) {
s_logger.error("OpenSAML Bootstrapping error: " + e.getMessage());
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "OpenSAML Bootstrapping error while creating SP MetaData", params, responseType));
}
if (params != null && params.containsKey("SAMLResponse")) {
try {
final String samlResponse = ((String[]) params.get(SAMLPluginConstants.SAML_RESPONSE))[0];
Response processedSAMLResponse = SAMLUtils.decodeSAMLResponse(samlResponse);
String statusCode = processedSAMLResponse.getStatus().getStatusCode().getValue();
if (!statusCode.equals(StatusCode.SUCCESS_URI)) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.INTERNAL_ERROR.getHttpCode(), "SAML SLO LogoutResponse status is not Success", params, responseType));
}
} catch (ConfigurationException | FactoryConfigurationError | ParserConfigurationException | SAXException | IOException | UnmarshallingException e) {
s_logger.error("SAMLResponse processing error: " + e.getMessage());
}
try {
resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
} catch (IOException ignored) {
s_logger.info("[ignored] second redirected sending failed.", ignored);
}
return responseString;
}
String idpId = (String) session.getAttribute(SAMLPluginConstants.SAML_IDPID);
SAMLProviderMetadata idpMetadata = _samlAuthManager.getIdPMetadata(idpId);
String nameId = (String) session.getAttribute(SAMLPluginConstants.SAML_NAMEID);
if (idpMetadata == null || nameId == null || nameId.isEmpty()) {
try {
resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
} catch (IOException ignored) {
s_logger.info("[ignored] final redirected failed.", ignored);
}
return responseString;
}
LogoutRequest logoutRequest = SAMLUtils.buildLogoutRequest(idpMetadata.getSloUrl(), _samlAuthManager.getSPMetadata().getEntityId(), nameId);
try {
String redirectUrl = idpMetadata.getSloUrl() + "?SAMLRequest=" + SAMLUtils.encodeSAMLRequest(logoutRequest);
resp.sendRedirect(redirectUrl);
} catch (MarshallingException | IOException e) {
s_logger.error("SAML SLO error: " + e.getMessage());
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Single Logout Error", params, responseType));
}
return responseString;
}
use of org.opensaml.saml.saml2.core.Response 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.opensaml.saml.saml2.core.Response in project ddf by codice.
the class AttributeQueryClaimsHandler method createClaims.
/**
* Creates claims from the extracted attributes.
*
* @param claimsCollection The collection of claims.
* @param assertion Assertion from the response.
* @return The collection of claims.
* @throws URISyntaxException
*/
protected ProcessedClaimCollection createClaims(ProcessedClaimCollection claimsCollection, Assertion assertion) throws URISyntaxException {
// Should only contain one Attribute Statement.
AttributeStatement attributeStatement = assertion.getAttributeStatements().get(0);
List<Attribute> attributeList = attributeStatement.getAttributes();
// and create the claim, otherwise, create the claim using its original attribute value.
for (Attribute attribute : attributeList) {
for (String claimType : supportedClaims) {
if (claimType.equalsIgnoreCase(attribute.getName())) {
String claimValue = attribute.getDOM().getTextContent();
if (attributeMap.containsKey(claimValue)) {
claimsCollection.add(createSingleValuedClaim(claimType, attributeMap.get(claimValue)));
} else {
claimsCollection.add(createSingleValuedClaim(claimType, claimValue));
}
break;
}
}
}
return claimsCollection;
}
use of org.opensaml.saml.saml2.core.Response in project ddf by codice.
the class AttributeQueryClient method retrieveResponse.
/**
* Retrieves the response and returns its SAML Assertion.
*
* @param requestDocument of the request.
* @return Assertion of the response or null if the response is empty.
* @throws AttributeQueryException
*/
private Assertion retrieveResponse(Document requestDocument) throws AttributeQueryException {
Assertion assertion = null;
try {
Document responseDocument = sendRequest(requestDocument);
if (responseDocument == null) {
return null;
}
// Print Response
if (LOGGER.isTraceEnabled()) {
printXML("SAML Response:\n {}", responseDocument);
}
// Extract Response from Soap message.
NodeList elementsByTagNameNS = responseDocument.getElementsByTagNameNS(SAML2_PROTOCOL, "Response");
if (elementsByTagNameNS == null) {
throw new AttributeQueryException("Unable to find SAML Response.");
}
Node responseNode = elementsByTagNameNS.item(0);
Element responseElement = (Element) responseNode;
Unmarshaller unmarshaller = XMLObjectProviderRegistrySupport.getUnmarshallerFactory().getUnmarshaller(responseElement);
Response response = (Response) unmarshaller.unmarshall(responseElement);
LOGGER.debug("Successfully marshalled Element to SAML Response.");
if (response.getStatus().getStatusCode().getValue().equals(SAML2_SUCCESS)) {
LOGGER.debug("Successful response, retrieved attributes.");
// Should only have one assertion.
assertion = response.getAssertions().get(0);
} else {
reportError(response.getStatus());
}
return assertion;
} catch (UnmarshallingException e) {
throw new AttributeQueryException("Unable to marshall Element to SAML Response.", e);
}
}
use of org.opensaml.saml.saml2.core.Response 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