use of javax.xml.stream.FactoryConfigurationError in project cloudstack by apache.
the class GetServiceProviderMetaDataCmd 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 {
SAMLMetaDataResponse response = new SAMLMetaDataResponse();
response.setResponseName(getCommandName());
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));
}
final SAMLProviderMetadata spMetadata = _samlAuthManager.getSPMetadata();
EntityDescriptor spEntityDescriptor = new EntityDescriptorBuilder().buildObject();
spEntityDescriptor.setEntityID(spMetadata.getEntityId());
SPSSODescriptor spSSODescriptor = new SPSSODescriptorBuilder().buildObject();
spSSODescriptor.setWantAssertionsSigned(true);
spSSODescriptor.setAuthnRequestsSigned(true);
X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
keyInfoGeneratorFactory.setEmitEntityCertificate(true);
KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();
KeyDescriptor signKeyDescriptor = new KeyDescriptorBuilder().buildObject();
signKeyDescriptor.setUse(UsageType.SIGNING);
KeyDescriptor encKeyDescriptor = new KeyDescriptorBuilder().buildObject();
encKeyDescriptor.setUse(UsageType.ENCRYPTION);
BasicX509Credential signingCredential = new BasicX509Credential();
signingCredential.setEntityCertificate(spMetadata.getSigningCertificate());
BasicX509Credential encryptionCredential = new BasicX509Credential();
encryptionCredential.setEntityCertificate(spMetadata.getEncryptionCertificate());
try {
signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingCredential));
encKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(encryptionCredential));
spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor);
spSSODescriptor.getKeyDescriptors().add(encKeyDescriptor);
} catch (SecurityException e) {
s_logger.warn("Unable to add SP X509 descriptors:" + e.getMessage());
}
NameIDFormat nameIDFormat = new NameIDFormatBuilder().buildObject();
nameIDFormat.setFormat(NameIDType.PERSISTENT);
spSSODescriptor.getNameIDFormats().add(nameIDFormat);
NameIDFormat emailNameIDFormat = new NameIDFormatBuilder().buildObject();
emailNameIDFormat.setFormat(NameIDType.EMAIL);
spSSODescriptor.getNameIDFormats().add(emailNameIDFormat);
NameIDFormat transientNameIDFormat = new NameIDFormatBuilder().buildObject();
transientNameIDFormat.setFormat(NameIDType.TRANSIENT);
spSSODescriptor.getNameIDFormats().add(transientNameIDFormat);
AssertionConsumerService assertionConsumerService = new AssertionConsumerServiceBuilder().buildObject();
assertionConsumerService.setIndex(1);
assertionConsumerService.setIsDefault(true);
assertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
assertionConsumerService.setLocation(spMetadata.getSsoUrl());
spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService);
AssertionConsumerService assertionConsumerService2 = new AssertionConsumerServiceBuilder().buildObject();
assertionConsumerService2.setIndex(2);
assertionConsumerService2.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
assertionConsumerService2.setLocation(spMetadata.getSsoUrl());
spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService2);
SingleLogoutService ssoService = new SingleLogoutServiceBuilder().buildObject();
ssoService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
ssoService.setLocation(spMetadata.getSloUrl());
spSSODescriptor.getSingleLogoutServices().add(ssoService);
SingleLogoutService ssoService2 = new SingleLogoutServiceBuilder().buildObject();
ssoService2.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
ssoService2.setLocation(spMetadata.getSloUrl());
spSSODescriptor.getSingleLogoutServices().add(ssoService2);
spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);
spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);
// Add technical contact
GivenName givenName = new GivenNameBuilder().buildObject();
givenName.setName(spMetadata.getContactPersonName());
EmailAddress emailAddress = new EmailAddressBuilder().buildObject();
emailAddress.setAddress(spMetadata.getContactPersonEmail());
ContactPerson contactPerson = new ContactPersonBuilder().buildObject();
contactPerson.setType(ContactPersonTypeEnumeration.TECHNICAL);
contactPerson.setGivenName(givenName);
contactPerson.getEmailAddresses().add(emailAddress);
spEntityDescriptor.getContactPersons().add(contactPerson);
// Add administrative/support contact
GivenName givenNameAdmin = new GivenNameBuilder().buildObject();
givenNameAdmin.setName(spMetadata.getContactPersonName());
EmailAddress emailAddressAdmin = new EmailAddressBuilder().buildObject();
emailAddressAdmin.setAddress(spMetadata.getContactPersonEmail());
ContactPerson contactPersonAdmin = new ContactPersonBuilder().buildObject();
contactPersonAdmin.setType(ContactPersonTypeEnumeration.ADMINISTRATIVE);
contactPersonAdmin.setGivenName(givenNameAdmin);
contactPersonAdmin.getEmailAddresses().add(emailAddressAdmin);
spEntityDescriptor.getContactPersons().add(contactPersonAdmin);
Organization organization = new OrganizationBuilder().buildObject();
OrganizationName organizationName = new OrganizationNameBuilder().buildObject();
organizationName.setName(new LocalizedString(spMetadata.getOrganizationName(), Locale.getDefault().getLanguage()));
OrganizationURL organizationURL = new OrganizationURLBuilder().buildObject();
organizationURL.setURL(new LocalizedString(spMetadata.getOrganizationUrl(), Locale.getDefault().getLanguage()));
organization.getOrganizationNames().add(organizationName);
organization.getURLs().add(organizationURL);
spEntityDescriptor.setOrganization(organization);
StringWriter stringWriter = new StringWriter();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Marshaller out = Configuration.getMarshallerFactory().getMarshaller(spEntityDescriptor);
out.marshall(spEntityDescriptor, document);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult streamResult = new StreamResult(stringWriter);
DOMSource source = new DOMSource(document);
transformer.transform(source, streamResult);
stringWriter.close();
response.setMetadata(stringWriter.toString());
} catch (ParserConfigurationException | IOException | MarshallingException | TransformerException e) {
if (responseType.equals(HttpUtils.JSON_CONTENT_TYPE)) {
response.setMetadata("Error creating Service Provider MetaData XML: " + e.getMessage());
} else {
return "Error creating Service Provider MetaData XML: " + e.getMessage();
}
}
// For JSON type return serialized response object
if (responseType.equals(HttpUtils.RESPONSE_TYPE_JSON)) {
return ApiResponseSerializer.toSerializedString(response, responseType);
}
// For other response types return XML
return stringWriter.toString();
}
use of javax.xml.stream.FactoryConfigurationError in project cloudstack by apache.
the class SAMLUtils method buildAuthnRequestUrl.
public static String buildAuthnRequestUrl(final String authnId, final SAMLProviderMetadata spMetadata, final SAMLProviderMetadata idpMetadata, final String signatureAlgorithm) {
String redirectUrl = "";
try {
DefaultBootstrap.bootstrap();
AuthnRequest authnRequest = SAMLUtils.buildAuthnRequestObject(authnId, spMetadata.getEntityId(), idpMetadata.getSsoUrl(), spMetadata.getSsoUrl());
PrivateKey privateKey = null;
if (spMetadata.getKeyPair() != null) {
privateKey = spMetadata.getKeyPair().getPrivate();
}
redirectUrl = idpMetadata.getSsoUrl() + "?" + SAMLUtils.generateSAMLRequestSignature("SAMLRequest=" + SAMLUtils.encodeSAMLRequest(authnRequest), privateKey, signatureAlgorithm);
} catch (ConfigurationException | FactoryConfigurationError | MarshallingException | IOException | NoSuchAlgorithmException | InvalidKeyException | java.security.SignatureException e) {
s_logger.error("SAML AuthnRequest message building error: " + e.getMessage());
}
return redirectUrl;
}
use of javax.xml.stream.FactoryConfigurationError 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 javax.xml.stream.FactoryConfigurationError in project openolat by klemens.
the class QTI12To21Converter method blockedHtml.
/**
* Make sure the HTML content is in block elements. Simple text
* are returned as is.
*
* @param text
* @return
*/
protected final String blockedHtml(String text) {
if (StringHelper.containsNonWhitespace(text)) {
collectMaterial(text);
if (StringHelper.isHtml(text)) {
String trimmedText = text.trim();
trimmedText = trimmedText.replace("<hr />", "<hr></hr>");
try {
Writer out = new StringWriter();
XMLOutputFactory xof = XMLOutputFactory.newInstance();
XMLStreamWriter xtw = xof.createXMLStreamWriter(out);
SAXParser parser = new SAXParser();
QTI12To21HtmlHandler handler = new QTI12To21HtmlHandler(xtw);
parser.setContentHandler(handler);
parser.parse(new InputSource(new StringReader(trimmedText)));
String blockedHtml = out.toString();
text = blockedHtml.replace("<start>", "").replace("</start>", "");
materialMappings.putAll(handler.getMaterialsMapping());
} catch (FactoryConfigurationError | XMLStreamException | SAXException | IOException e) {
log.error("", e);
}
} else {
text = StringEscapeUtils.unescapeHtml(text);
}
}
return text;
}
use of javax.xml.stream.FactoryConfigurationError in project wso2-synapse by wso2.
the class JsonStreamFactory method newFactory.
/**
* <p>Create a new instance of a JsonStreamFactory.</p>
* <p>Determines the class to instantiate as follows:
* <ol>
* <li>Use the Services API (as detailed in the JAR specification). If a resource with the name
* of META-INF/services/de.odysseus.staxon.json.stream.JsonStreamFactory exists, then its first line,
* if present, is used as the UTF-8 encoded name of the implementation class.</li>
* <li>Use the properties file "lib/staxon.properties" in the JRE directory. If this file exists
* and is readable by the java.util.Properties.load(InputStream) method, and it contains an entry
* whose key is "de.odysseus.staxon.json.stream.JsonStreamFactory", then the value of that entry is
* used as the name of the implementation class.</li>
* <li>Use the de.odysseus.staxon.json.stream.JsonStreamFactory system property. If a system property
* with this name is defined, then its value is used as the name of the implementation class.</li>
* <li>Use platform default: "de.odysseus.staxon.json.stream.impl.JsonStreamFactoryImpl".</li>
* </ol>
* </p>
*
* @return An instance of JsonStreamFactory.
* @throws FactoryConfigurationError if a factory class cannot be found or instantiation fails.
*/
public static JsonStreamFactory newFactory() throws FactoryConfigurationError {
ClassLoader classLoader;
try {
classLoader = Thread.currentThread().getContextClassLoader();
} catch (SecurityException e) {
classLoader = JsonStreamFactory.class.getClassLoader();
}
String className = getMetaInfServicesClassName(JsonStreamFactory.class, classLoader);
if (className == null || className.trim().length() == 0) {
className = getJavaHomeLibClassName(JsonStreamFactory.class, "staxon");
}
if (className == null || className.trim().length() == 0) {
try {
className = System.getProperty(JsonStreamFactory.class.getName());
} catch (Exception se) {
// do nothing
}
}
if (className == null || className.trim().length() == 0) {
className = "org.apache.synapse.commons.staxon.core.json.stream.impl.JsonStreamFactoryImpl";
}
try {
return (JsonStreamFactory) classLoader.loadClass(className).newInstance();
} catch (Throwable e) {
throw new FactoryConfigurationError("Error creating stream factory: " + e);
}
}
Aggregations