Java Examples for org.apache.cxf.binding.soap.SoapMessage
The following java examples will help you to understand the usage of org.apache.cxf.binding.soap.SoapMessage. These source code samples are taken from different open source projects.
Example 1
| Project: support-examples-master File: RemoveSoapActionInterceptor.java View source code |
public void handleMessage(Message m) throws Fault {
if (!(m instanceof SoapMessage)) {
return;
}
SoapMessage message = (SoapMessage) m;
Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
if (headers != null) {
headers.remove(SoapBindingConstants.SOAP_ACTION);
}
}Example 2
| Project: grisu-connectors-master File: MyProxyAuthInterceptor.java View source code |
public void handleMessage(SoapMessage message) throws Fault {
final Header header = message.getHeader(new QName("", "myProxyCredentials"));
try {
MyProxyCredentials cred = null;
ProxyCredential proxyCredential = (ProxyCredential) message.getExchange().getSession().get("credential");
System.out.println("the credential is " + proxyCredential);
if (proxyCredential == null || !proxyCredential.isValid()) {
myLogger.debug("creating new credential...");
cred = retrieveProxyFromHeader(header);
proxyCredential = createProxyCredential(cred.username, cred.password, cred.myproxyServer, Integer.parseInt(cred.myproxyPort), 99999);
message.getExchange().getSession().put("credential", proxyCredential);
}
if (proxyCredential == null || !proxyCredential.isValid()) {
throw new Fault(new LoginException(cred.username, cred.password));
}
message.put("credential", proxyCredential);
} catch (final JAXBException ex) {
throw new Fault(ex);
}
}Example 3
| Project: tesb-rt-se-master File: RequestCallbackInInterceptor.java View source code |
/**
* {@inheritDoc}
*/
@Override
public void handleMessage(SoapMessage message) throws Fault {
final Header callHeader = message.getHeader(RequestCallbackFeature.CALL_ID_HEADER_NAME);
if (callHeader == null) {
return;
}
final Exchange e = message.getExchange();
if (!e.isOneWay()) {
e.setOneWay(true);
}
final Header callbackHeader = message.getHeader(RequestCallbackFeature.CALLBACK_ID_HEADER_NAME);
if (callbackHeader == null) {
doHandleRequestSoapMessage(message, callHeader);
} else {
doHandleCallbackSoapMessage(message, callHeader, callbackHeader);
}
}Example 4
| Project: glowroot-master File: SoapOutInterceptorAspect.java View source code |
@OnBefore
@Nullable
public static TraceEntry onBefore(ThreadContext context, @BindParameter @Nullable SoapMessage message) {
if (message == null) {
return null;
}
Object methodObj = message.getContextualProperty("javax.xml.ws.http.request.method");
String method;
if (methodObj == null) {
method = "";
} else {
method = methodObj.toString() + " ";
}
Object uriObj = message.getContextualProperty("javax.xml.ws.wsdl.description");
String uri;
if (uriObj == null) {
uri = "";
} else {
uri = uriObj.toString();
}
Object operationObj = message.getContextualProperty("javax.xml.ws.wsdl.operation");
String operationName;
if (operationObj instanceof QName) {
operationName = ", operation=" + ((QName) operationObj).getLocalPart();
} else {
operationName = "";
}
return context.startServiceCallEntry("HTTP", method + Uris.stripQueryString(uri), MessageSupplier.create("cxf client soap request: {}{}{}", method, uri, operationName), timerName);
}Example 5
| Project: camel-master File: CxfMessageSoapHeaderOutInterceptor.java View source code |
public void handleMessage(SoapMessage message) {
// remove the soap header to avoid the endless loop
SOAPMessage saaj = message.getContent(SOAPMessage.class);
if (saaj != null) {
// AS CXF_MESSAGE already build up all the SOAP message
// need to clean up the soap Header from message to avoid endless loop
message.getHeaders().clear();
}
}Example 6
| Project: Consent2Share-master File: ContentTypeRebuildingOutboundSoapInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage message) throws Fault {
debug(() -> message.toString());
debug(() -> new StringBuilder().append(CONTENT_TYPE).append(" before modification: ").append(message.get(CONTENT_TYPE).toString()).toString());
final String contentType = (String) message.get(CONTENT_TYPE);
final List<Pair> contentTypeList = new ArrayList<>();
try (Scanner scanner = new Scanner(contentType)) {
scanner.useDelimiter(SEMICOLON);
while (scanner.hasNext()) {
final String next = scanner.next();
final String[] split = next.split(EQUAL);
contentTypeList.add(new Pair(clean(split, IDX_KEY), split.length > IDX_VALUE ? Optional.of(clean(split, IDX_VALUE)) : Optional.empty()));
}
}
final String correctedContentType = contentTypeList.stream().map(ContentTypeRebuildingOutboundSoapInterceptor::toCorrectedContentType).collect(joining(SEMICOLON_WITH_SPACE));
debug(() -> new StringBuilder().append(CONTENT_TYPE).append(" after modification: ").append(correctedContentType).toString());
message.put(CONTENT_TYPE, correctedContentType);
}Example 7
| Project: cxf-master File: RetransmissionQueueImpl.java View source code |
public void resend(Message message, boolean requestAcknowledge) {
RMProperties properties = RMContextUtils.retrieveRMProperties(message, true);
SequenceType st = properties.getSequence();
if (st != null) {
LOG.log(Level.INFO, "RESEND_MSG", st.getMessageNumber());
}
if (message instanceof SoapMessage) {
doResend((SoapMessage) message);
} else {
doResend(new SoapMessage(message));
}
}Example 8
| Project: elpaaso-core-master File: LogInInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage msg) throws Fault {
HttpServletRequest request = (HttpServletRequest) msg.get(AbstractHTTPDestination.HTTP_REQUEST);
if (null != request) {
String addr = request.getRemoteAddr();
MDC.put(LOG_KEY_REMOTE_ADDR, addr);
if (request.getSession() != null) {
String sessionId = request.getSession().getId();
MDC.put(LOG_KEY_SESSION_ID, sessionId);
}
}
}Example 9
| Project: jboss-fuse-examples-master File: HTTPMethodInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage message) throws Fault {
HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
if (request != null) {
if (!HTTP_METHODS.get(request.getMethod())) {
throw new Fault(new IllegalArgumentException("Invalid HTTPMethod of " + request.getMethod()));
}
}
}Example 10
| Project: motown-master File: ReplyToHeaderInterceptorTest.java View source code |
@Test
public void handleMessageWithMapsVerifyReplyToHeaderAdded() {
AddressingProperties properties = new AddressingPropertiesImpl();
Message message = new MessageImpl();
message.put(MAP_PROPERTY, properties);
ReplyToHeaderInInterceptor headerInInterceptor = new ReplyToHeaderInInterceptor();
headerInInterceptor.handleMessage(new SoapMessage(message));
assertEquals(REPLY_TO_ANONYMOUS, properties.getReplyTo().getAddress().getValue());
}Example 11
| Project: opencmis-master File: UsernameTokenInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage message) {
// don't extract a user, if there is already one
if (getCurrentUser(message) == null) {
Header securityHeader = message.getHeader(WSSE_SECURITY);
if (securityHeader != null) {
if (!(securityHeader.getObject() instanceof Node)) {
throw new CmisRuntimeException("Cannot read Security header.");
}
Node usernameTokenNode = getUsernameTokenNode((Node) securityHeader.getObject());
if (usernameTokenNode == null) {
return;
}
String username = getUsername(usernameTokenNode);
if (username == null) {
return;
}
String password = getPassword(usernameTokenNode);
setUserAndPassword(message, username, password);
}
}
}Example 12
| Project: rapid-framework-master File: DistributedThreadLocalOutSOAPHeaderInterceptor.java View source code |
public void handleMessage(SoapMessage message) throws Fault {
DistributedThreadLocal.onBeforeRemoteCall();
List<Header> headers = message.getHeaders();
Map<String, String> threadlocalMap = DistributedThreadLocal.getMap();
for (Map.Entry<String, String> entry : threadlocalMap.entrySet()) {
headers.add(getHeader(entry.getKey(), entry.getValue()));
}
}Example 13
| Project: cyclos-master File: AuthInterceptor.java View source code |
@Override
public void handleMessage(final SoapMessage message) throws Fault {
final HttpServletRequest request = WebServiceHelper.requestOf(message);
request.setAttribute(ContextType.class.getName(), ContextType.SERVICE_CLIENT);
ServiceClient client = null;
final ServletContext servletContext = servletContextOf(message);
try {
if (!applicationServiceLocal.isOnline()) {
throw WebServiceHelper.fault(WebServiceFaultsEnum.APPLICATION_OFFLINE);
}
// Check non-secure access when HTTP is enabled
if (Boolean.TRUE.equals(servletContext.getAttribute("cyclos.httpEnabled"))) {
final String protocol = StringUtils.split(request.getRequestURL().toString(), "://")[0];
if (!"https".equalsIgnoreCase(protocol)) {
throw WebServiceHelper.fault(WebServiceFaultsEnum.SECURE_ACCESS_REQUIRED);
}
}
boolean allowed = false;
// Find the service client
client = resolveClient(request);
if (client != null) {
// Find the requested operation
final ServiceOperation[] operations = resolveOperations(message);
if (operations.length == 0) {
// When there are no operations, access is granted to anyone
allowed = true;
} else {
// Check whether the client has access to the requested operation
final Set<ServiceOperation> permissions = client.getPermissions();
for (final ServiceOperation serviceOperation : operations) {
if (permissions.contains(serviceOperation)) {
allowed = true;
break;
}
}
}
}
if (!allowed) {
throw WebServiceHelper.fault(WebServiceFaultsEnum.UNAUTHORIZED_ACCESS);
}
// Initialize the logged user
LoggedUser.init(client, request.getRemoteAddr(), null);
// Initialize the context
WebServiceContext.set(client, servletContext, request, message);
} catch (Exception e) {
WebServiceHelper.initializeContext(message);
if (e instanceof SoapFault) {
throw (SoapFault) e;
} else {
throw WebServiceHelper.fault(e);
}
}
}Example 14
| Project: libresonic-master File: SonosFaultInterceptor.java View source code |
/*
* Only handles instances of SonosSoapFault, all other exceptions fall through to the default Fault Interceptor
*/
@Override
public void handleMessage(SoapMessage message) throws Fault {
Fault fault = (Fault) message.getContent(Exception.class);
LOG.warn("Error: " + fault, fault);
if (fault.getCause() instanceof SonosSoapFault) {
SonosSoapFault cause = (SonosSoapFault) fault.getCause();
fault.setFaultCode(new QName(cause.getFaultCode()));
fault.setMessage(cause.getFaultCode());
Document document = DOMUtils.createDocument();
Element details = document.createElement("detail");
fault.setDetail(details);
details.appendChild(document.createElement("ExceptionInfo"));
Element sonosError = document.createElement("SonosError");
sonosError.setTextContent(String.valueOf(cause.getSonosError()));
details.appendChild(sonosError);
}
}Example 15
| Project: cxf-fediz-master File: CustomUTValidator.java View source code |
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
if (credential == null || credential.getUsernametoken() == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
}
// Need to use SAAJ to get the SOAP Body as we are just using the UsernameTokenInterceptor
SOAPMessage soapMessage = getSOAPMessage((SoapMessage) data.getMsgContext());
try {
Element soapBody = SAAJUtils.getBody(soapMessage);
if (soapBody != null) {
// Find custom Element in the SOAP Body
Element realm = XMLUtils.findElement(soapBody, "realm", "http://cxf.apache.org/custom");
if (realm != null) {
String realmStr = realm.getTextContent();
if ("custom-realm".equals(realmStr)) {
UsernameTokenValidator validator = new UsernameTokenValidator();
return validator.validate(credential, data);
}
}
}
} catch (SOAPException ex) {
}
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
}Example 16
| Project: ddf-master File: IdpEndpoint.java View source code |
private AuthObj determineAuthMethod(String bodyStr, AuthnRequest authnRequest) {
XMLStreamReader xmlStreamReader = null;
try {
xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(bodyStr));
} catch (XMLStreamException e) {
LOGGER.debug("Unable to parse SOAP message from client.", e);
}
SoapMessage soapMessage = new SoapMessage(Soap11.getInstance());
SAAJInInterceptor.SAAJPreInInterceptor preInInterceptor = new SAAJInInterceptor.SAAJPreInInterceptor();
soapMessage.setContent(XMLStreamReader.class, xmlStreamReader);
preInInterceptor.handleMessage(soapMessage);
SAAJInInterceptor inInterceptor = new SAAJInInterceptor();
inInterceptor.handleMessage(soapMessage);
SOAPPart soapMessageContent = (SOAPPart) soapMessage.getContent(Node.class);
AuthObj authObj = new AuthObj();
try {
Iterator soapHeaderElements = soapMessageContent.getEnvelope().getHeader().examineAllHeaderElements();
while (soapHeaderElements.hasNext()) {
SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) soapHeaderElements.next();
if (soapHeaderElement.getLocalName().equals("Security")) {
Iterator childElements = soapHeaderElement.getChildElements();
while (childElements.hasNext()) {
Object nextElement = childElements.next();
if (nextElement instanceof SOAPElement) {
SOAPElement element = (SOAPElement) nextElement;
if (element.getLocalName().equals("UsernameToken")) {
Iterator usernameTokenElements = element.getChildElements();
Object next;
while (usernameTokenElements.hasNext()) {
if ((next = usernameTokenElements.next()) instanceof Element) {
Element nextEl = (Element) next;
if (nextEl.getLocalName().equals("Username")) {
authObj.username = nextEl.getTextContent();
} else if (nextEl.getLocalName().equals("Password")) {
authObj.password = nextEl.getTextContent();
}
}
}
if (authObj.username != null && authObj.password != null) {
authObj.method = USER_PASS;
break;
}
} else if (element.getLocalName().equals("Assertion") && element.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
authObj.assertion = new SecurityToken(element.getAttribute("ID"), element, null, null);
authObj.method = SAML;
break;
}
}
}
}
}
} catch (SOAPException e) {
LOGGER.debug("Unable to parse SOAP message.", e);
}
RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
boolean requestingPki = false;
boolean requestingUp = false;
if (requestedAuthnContext != null) {
List<AuthnContextClassRef> authnContextClassRefs = requestedAuthnContext.getAuthnContextClassRefs();
for (AuthnContextClassRef authnContextClassRef : authnContextClassRefs) {
String authnContextClassRefStr = authnContextClassRef.getAuthnContextClassRef();
if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SMARTCARD_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SOFTWARE_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SPKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_TLS_CLIENT.equals(authnContextClassRefStr)) {
requestingPki = true;
} else if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD_PROTECTED_TRANSPORT.equals(authnContextClassRefStr)) {
requestingUp = true;
}
}
} else {
//The requested auth context isn't required so we don't know what they want... just set both to true
requestingPki = true;
requestingUp = true;
}
if (requestingUp && authObj.method != null && authObj.method.equals(USER_PASS)) {
LOGGER.trace("Found UsernameToken and correct AuthnContextClassRef");
return authObj;
} else if (requestingPki && authObj.method == null) {
LOGGER.trace("Found no token, but client requested PKI AuthnContextClassRef");
authObj.method = PKI;
return authObj;
} else if (authObj.method == null) {
LOGGER.debug("No authentication tokens found for the current request and the client did not request PKI authentication");
}
return authObj;
}Example 17
| Project: ddf-platform-master File: AnonymousInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage message) throws Fault {
if (anonymousAccessDenied) {
LOGGER.debug("AnonymousAccess not enabled - no message checking performed.");
return;
}
if (message != null) {
SoapVersion version = message.getVersion();
SOAPMessage soapMessage = getSOAPMessage(message);
SOAPFactory soapFactory = null;
SOAPElement securityHeader = null;
//Check if security header exists; if not, execute AnonymousInterceptor logic
String actor = (String) getOption(WSHandlerConstants.ACTOR);
if (actor == null) {
actor = (String) message.getContextualProperty(SecurityConstants.ACTOR);
}
Element existingSecurityHeader = null;
try {
existingSecurityHeader = WSSecurityUtil.getSecurityHeader(soapMessage.getSOAPPart(), actor);
} catch (WSSecurityException e1) {
LOGGER.debug("Issue with getting security header", e1);
}
if (existingSecurityHeader == null) {
LOGGER.debug("Current request has no security header, continuing with AnonymousInterceptor");
AssertionInfoMap assertionInfoMap = message.get(AssertionInfoMap.class);
// if there is a policy we need to follow or we are ignoring policies, prepare the SOAP message
if ((assertionInfoMap != null) || overrideEndpointPolicies) {
RequestData reqData = new CXFRequestData();
WSSConfig config = (WSSConfig) message.getContextualProperty(WSSConfig.class.getName());
WSSecurityEngine engine = null;
if (config != null) {
engine = new WSSecurityEngine();
engine.setWssConfig(config);
}
if (engine == null) {
engine = new WSSecurityEngine();
config = engine.getWssConfig();
}
reqData.setWssConfig(config);
try {
soapFactory = SOAPFactory.newInstance();
} catch (SOAPException e) {
LOGGER.error("Could not create a SOAPFactory.", e);
return;
}
if (soapFactory != null) {
//Create security header
try {
securityHeader = soapFactory.createElement(WSConstants.WSSE_LN, WSConstants.WSSE_PREFIX, WSConstants.WSSE_NS);
securityHeader.addAttribute(new QName(WSConstants.URI_SOAP11_ENV, WSConstants.ATTR_MUST_UNDERSTAND), "1");
} catch (SOAPException e) {
LOGGER.error("Unable to create security header for anonymous user.", e);
return;
}
}
}
EffectivePolicy effectivePolicy = message.get(EffectivePolicy.class);
Exchange exchange = message.getExchange();
BindingOperationInfo bindingOperationInfo = exchange.getBindingOperationInfo();
Endpoint endpoint = exchange.get(Endpoint.class);
if (null == endpoint) {
return;
}
EndpointInfo endpointInfo = endpoint.getEndpointInfo();
Bus bus = exchange.get(Bus.class);
PolicyEngine policyEngine = bus.getExtension(PolicyEngine.class);
if (effectivePolicy == null) {
if (policyEngine != null) {
if (MessageUtils.isRequestor(message)) {
effectivePolicy = policyEngine.getEffectiveClientResponsePolicy(endpointInfo, bindingOperationInfo, message);
} else {
effectivePolicy = policyEngine.getEffectiveServerRequestPolicy(endpointInfo, bindingOperationInfo, message);
}
}
}
//Auto analyze endpoint policies
//Token Assertions
String tokenAssertion = null;
String tokenType = null;
//Security Binding Assertions
boolean layoutLax = false;
boolean layoutStrict = false;
boolean layoutLaxTimestampFirst = false;
boolean layoutLaxTimestampLast = false;
boolean requireClientCert = false;
QName secBindingAssertion = null;
//Supporting Token Assertions
QName supportingTokenAssertion = null;
boolean policyRequirementsSupported = false;
// if there is a policy, try to follow it as closely as possible
if (effectivePolicy != null) {
Policy policy = effectivePolicy.getPolicy();
if (policy != null) {
AssertionInfoMap infoMap = new AssertionInfoMap(policy);
Set<Map.Entry<QName, Collection<AssertionInfo>>> entries = infoMap.entrySet();
for (Map.Entry<QName, Collection<AssertionInfo>> entry : entries) {
Collection<AssertionInfo> assetInfoList = entry.getValue();
for (AssertionInfo info : assetInfoList) {
LOGGER.debug("Assertion Name: {}", info.getAssertion().getName().getLocalPart());
QName qName = info.getAssertion().getName();
StringWriter out = new StringWriter();
XMLStreamWriter writer = null;
try {
writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
} catch (XMLStreamException e) {
LOGGER.debug("Error with XMLStreamWriter", e);
} catch (FactoryConfigurationError e) {
LOGGER.debug("Error with FactoryConfiguration", e);
}
try {
if (writer != null) {
info.getAssertion().serialize(writer);
writer.flush();
}
} catch (XMLStreamException e) {
LOGGER.debug("Error with XMLStream", e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (XMLStreamException ignore) {
}
}
}
LOGGER.trace("Assertion XML: {}", out.toString());
String xml = out.toString();
// TODO DDF-1205 complete support for dynamic policy handling
if (qName.equals(SP12Constants.TRANSPORT_BINDING)) {
secBindingAssertion = qName;
} else if (qName.equals(SP12Constants.INCLUDE_TIMESTAMP)) {
createIncludeTimestamp(soapFactory, securityHeader);
} else if (qName.equals(SP12Constants.LAYOUT)) {
String xpathLax = "/Layout/Policy/Lax";
String xpathStrict = "/Layout/Policy/Strict";
String xpathLaxTimestampFirst = "/Layout/Policy/LaxTimestampFirst";
String xpathLaxTimestampLast = "/Layout/Policy/LaxTimestampLast";
} else if (qName.equals(SP12Constants.TRANSPORT_TOKEN)) {
} else if (qName.equals(SP12Constants.HTTPS_TOKEN)) {
String xpath = "/HttpsToken/Policy/RequireClientCertificate";
} else if (qName.equals(SP12Constants.SIGNED_SUPPORTING_TOKENS)) {
String xpath = "/SignedSupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType";
tokenType = retrieveXmlValue(xml, xpath);
supportingTokenAssertion = qName;
} else if (qName.equals(SP12Constants.SUPPORTING_TOKENS)) {
String xpath = "/SupportingTokens/Policy//IssuedToken/RequestSecurityTokenTemplate/TokenType";
tokenType = retrieveXmlValue(xml, xpath);
supportingTokenAssertion = qName;
} else if (qName.equals(org.apache.cxf.ws.addressing.policy.MetadataConstants.ADDRESSING_ASSERTION_QNAME)) {
createAddressing(message, soapMessage, soapFactory);
} else if (qName.equals(SP12Constants.TRUST_13)) {
} else if (qName.equals(SP12Constants.ISSUED_TOKEN)) {
//Check Token Assertion
String xpath = "/IssuedToken/@IncludeToken";
tokenAssertion = retrieveXmlValue(xml, xpath);
} else if (qName.equals(SP12Constants.WSS11)) {
}
}
}
//Check security and token policies
if (tokenAssertion != null && tokenType != null && tokenAssertion.trim().equals(SP12Constants.INCLUDE_ALWAYS_TO_RECIPIENT) && tokenType.trim().equals(TOKEN_SAML20)) {
policyRequirementsSupported = true;
} else {
LOGGER.warn("AnonymousInterceptor does not support the policies presented by the endpoint.");
}
} else {
if (overrideEndpointPolicies) {
LOGGER.debug("WS Policy is null, override is true - an anonymous assertion will be generated");
} else {
LOGGER.warn("WS Policy is null, override flag is false - no anonymous assertion will be generated.");
}
}
} else {
if (overrideEndpointPolicies) {
LOGGER.debug("Effective WS Policy is null, override is true - an anonymous assertion will be generated");
} else {
LOGGER.warn("Effective WS Policy is null, override flag is false - no anonymous assertion will be generated.");
}
}
if (policyRequirementsSupported || overrideEndpointPolicies) {
LOGGER.debug("Creating anonymous security token.");
if (soapFactory != null) {
createSecurityToken(version, soapFactory, securityHeader);
try {
// Add security header to SOAP message
soapMessage.getSOAPHeader().addChildElement(securityHeader);
} catch (SOAPException e) {
LOGGER.error("Issue when adding security header to SOAP message:" + e.getMessage());
}
} else {
LOGGER.debug("Security Header was null so not creating a SAML Assertion");
}
}
} else {
LOGGER.debug("SOAP message contains security header, no action taken by the AnonymousInterceptor.");
}
if (LOGGER.isTraceEnabled()) {
try {
LOGGER.trace("SOAP request after anonymous interceptor: {}", SecurityLogger.getFormattedXml(soapMessage.getSOAPHeader().getParentNode()));
} catch (SOAPException e) {
}
}
} else {
LOGGER.error("Incoming SOAP message is null - anonymous interceptor makes no sense.");
}
}Example 18
| Project: jbossws-cxf-master File: SubjectCreatingInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage msg) throws Fault {
Endpoint ep = msg.getExchange().get(Endpoint.class);
sdc.set(ep.getSecurityDomainContext());
try {
SecurityToken token = msg.get(SecurityToken.class);
SecurityContext context = msg.get(SecurityContext.class);
if (token == null || context == null || context.getUserPrincipal() == null) {
super.handleMessage(msg);
return;
}
UsernameToken ut = (UsernameToken) token;
Subject subject = createSubject(ut.getName(), ut.getPassword(), ut.isHashed(), ut.getNonce(), ut.getCreatedTime());
SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
msg.put(SecurityContext.class, sc);
} finally {
if (sdc != null) {
sdc.remove();
}
}
}Example 19
| Project: release-master File: AddressingInterceptor.java View source code |
/**
* {@inheritDoc}
*/
@Override
public void handleMessage(SoapMessage message) throws Fault {
if (ContextUtils.isOutbound(message)) {
AddressingProperties maps = ContextUtils.retrieveMAPs(message, false, true, false);
WrappedMessageContext soapContext = new WrappedMessageContext(message, Scope.APPLICATION);
if (soapContext.containsKey(SOAPUtil.SWITCHYARD_CONTEXT)) {
Context context = (Context) soapContext.get(SOAPUtil.SWITCHYARD_CONTEXT);
String property = (String) context.getPropertyValue(SOAPUtil.WSA_ACTION_STR);
AttributedURIType uri = null;
EndpointReferenceType ref = null;
if (property != null) {
uri = new AttributedURIType();
uri.setValue(property);
maps.setAction(uri);
}
property = (String) context.getPropertyValue(SOAPUtil.WSA_FROM_STR);
if (property != null) {
uri = new AttributedURIType();
uri.setValue(property);
ref = new EndpointReferenceType();
ref.setAddress(uri);
maps.setFrom(ref);
}
property = (String) context.getPropertyValue(SOAPUtil.WSA_TO_STR);
if (property != null) {
uri = new AttributedURIType();
uri.setValue(property);
ref = new EndpointReferenceType();
ref.setAddress(uri);
maps.setTo(ref);
}
property = (String) context.getPropertyValue(SOAPUtil.WSA_FAULTTO_STR);
if (property != null) {
uri = new AttributedURIType();
uri.setValue(property);
ref = new EndpointReferenceType();
ref.setAddress(uri);
maps.setFaultTo(ref);
}
property = (String) context.getPropertyValue(SOAPUtil.WSA_REPLYTO_STR);
if (property != null) {
uri = new AttributedURIType();
uri.setValue(property);
ref = new EndpointReferenceType();
ref.setAddress(uri);
maps.setReplyTo(ref);
}
property = (String) context.getPropertyValue(SOAPUtil.WSA_RELATESTO_STR);
if (property != null) {
RelatesToType relatesTo = new RelatesToType();
relatesTo.setValue(property);
maps.setRelatesTo(relatesTo);
}
property = (String) context.getPropertyValue(SOAPUtil.WSA_MESSAGEID_STR);
if (property != null) {
uri = new AttributedURIType();
uri.setValue(property);
maps.setMessageID(uri);
}
}
}
}Example 20
| Project: steve-master File: MediatorInInterceptor.java View source code |
public final void handleMessage(SoapMessage message) {
String schemaNamespace = "";
InterceptorChain chain = message.getInterceptorChain();
// Scan the incoming message for its schema namespace
try {
// Create a buffered stream so that we get back the original stream after scanning
InputStream is = message.getContent(InputStream.class);
BufferedInputStream bis = new BufferedInputStream(is);
bis.mark(bis.available());
message.setContent(InputStream.class, bis);
String encoding = (String) message.get(Message.ENCODING);
XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(bis, encoding);
DepthXMLStreamReader xmlReader = new DepthXMLStreamReader(reader);
if (xmlReader.nextTag() == XMLStreamConstants.START_ELEMENT) {
String ns = xmlReader.getNamespaceURI();
SoapVersion soapVersion = SoapVersionFactory.getInstance().getSoapVersion(ns);
// Advance just past header
StaxUtils.toNextTag(xmlReader, soapVersion.getBody());
// Past body
xmlReader.nextTag();
}
schemaNamespace = xmlReader.getName().getNamespaceURI();
bis.reset();
} catch (IOExceptionXMLStreamException | ex) {
log.error("Exception happened", ex);
}
// Init the lookup, when the first message ever arrives
if (actualServers.isEmpty()) {
initServerLookupMap(message);
}
// We redirect the message to the actual OCPP service
Server targetServer = actualServers.get(schemaNamespace);
// Redirect the request
if (targetServer != null) {
MessageObserver mo = targetServer.getDestination().getMessageObserver();
mo.onMessage(message);
}
// Now the response has been put in the message, abort the chain
chain.abort();
}Example 21
| Project: gatein-wsrp-master File: GTNSubjectCreatingInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage msg) throws Fault {
String actionProperty = (String) this.getProperties().get(WSHandlerConstants.ACTION);
if (actionProperty.contains(USERNAME_TOKEN_IFAVAILABLE)) {
gtnUsernameTokenIfAvailable = true;
this.setProperty(WSHandlerConstants.ACTION, actionProperty.replace(USERNAME_TOKEN_IFAVAILABLE, WSHandlerConstants.USERNAME_TOKEN));
}
try {
//handle the message here which will create the SecurityContext containing the username and password
super.handleMessage(msg);
} finally {
//Note: needed since on the next invocation, the user may have logged out but the action property will have already been set as "UsernameToken" and the above checks will not be performed.
if (gtnUsernameTokenIfAvailable) {
this.setProperty(WSHandlerConstants.ACTION, actionProperty);
}
}
HttpServletRequest request = (HttpServletRequest) msg.get("HTTP.REQUEST");
if (wsUsernameTokenPrincipal != null) {
String username = wsUsernameTokenPrincipal.getName();
String password = wsUsernameTokenPrincipal.getPassword();
wsUsernameTokenPrincipal = null;
try {
//only perform a login if the user is not already authenticated
if (request.getRemoteUser() == null) {
request.login(username, password);
}
} catch (ServletException e) {
e.printStackTrace();
}
} else // This handles the situations where ws-security was enabled, but has currently been disabled for the consumer
if (request.getRemoteUser() != null) {
try {
request.logout();
} catch (ServletException e) {
e.printStackTrace();
}
}
}Example 22
| Project: midpoint-master File: SpringAuthenticationInjectorInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage message) throws Fault {
//Note: in constructor we have specified that we will be called after we have been successfully authenticated the user through WS-Security
//Now we will only set the Spring Authentication object based on the user found in the header
LOGGER.trace("Intercepted message: {}", message);
SOAPMessage saajSoapMessage = securityHelper.getSOAPMessage(message);
if (saajSoapMessage == null) {
LOGGER.error("No soap message in handler");
throw createFault(WSSecurityException.ErrorCode.FAILURE);
}
ConnectionEnvironment connEnv = new ConnectionEnvironment();
connEnv.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
String username = null;
try {
username = securityHelper.getUsernameFromMessage(saajSoapMessage);
LOGGER.trace("Attempt to authenticate user '{}'", username);
if (StringUtils.isBlank(username)) {
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "Empty username");
throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
MidPointPrincipal principal;
try {
principal = userDetailsService.getPrincipal(username);
} catch (SchemaException e) {
LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "Schema error: " + e.getMessage());
throw new Fault(e);
}
LOGGER.trace("Principal: {}", principal);
if (principal == null) {
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "No user");
throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
// Account validity and credentials and all this stuff should be already checked
// in the password callback
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null);
SecurityContextHolder.getContext().setAuthentication(authentication);
String operationName;
try {
operationName = DOMUtil.getFirstChildElement(saajSoapMessage.getSOAPBody()).getLocalName();
} catch (SOAPException e) {
LOGGER.debug("Access to web service denied for user '{}': SOAP error: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "SOAP error: " + e.getMessage());
throw new Fault(e);
}
// AUTHORIZATION
boolean isAuthorized;
try {
isAuthorized = securityEnforcer.isAuthorized(AuthorizationConstants.AUTZ_WS_ALL_URL, AuthorizationPhaseType.REQUEST, null, null, null, null);
LOGGER.trace("Determined authorization for web service access (action: {}): {}", AuthorizationConstants.AUTZ_WS_ALL_URL, isAuthorized);
} catch (SchemaException e) {
LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Schema error: " + e.getMessage());
throw createFault(WSSecurityException.ErrorCode.FAILURE);
}
if (!isAuthorized) {
String action = QNameUtil.qNameToUri(new QName(AuthorizationConstants.NS_AUTHORIZATION_WS, operationName));
try {
isAuthorized = securityEnforcer.isAuthorized(action, AuthorizationPhaseType.REQUEST, null, null, null, null);
LOGGER.trace("Determined authorization for web service operation {} (action: {}): {}", operationName, action, isAuthorized);
} catch (SchemaException e) {
LOGGER.debug("Access to web service denied for user '{}': schema error: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Schema error: " + e.getMessage());
throw createFault(WSSecurityException.ErrorCode.FAILURE);
}
}
if (!isAuthorized) {
LOGGER.debug("Access to web service denied for user '{}': not authorized", username);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Not authorized");
throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
} catch (WSSecurityException e) {
LOGGER.debug("Access to web service denied for user '{}': security exception: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "Security exception: " + e.getMessage());
throw new Fault(e, e.getFaultCode());
} catch (ObjectNotFoundException e) {
LOGGER.debug("Access to web service denied for user '{}': object not found: {}", username, e.getMessage(), e);
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
securityHelper.auditLoginFailure(username, null, connEnv, "No user");
throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
}
// Avoid auditing login attempt again if the operation fails on internal authorization
message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true);
LOGGER.debug("Access to web service allowed for user '{}'", username);
}Example 23
| Project: tomee-master File: EjbInterceptor.java View source code |
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception {
Endpoint endpoint = this.exchange.get(Endpoint.class);
Service service = endpoint.getService();
Binding binding = ((JaxWsEndpointImpl) endpoint).getJaxwsBinding();
this.exchange.put(InvocationContext.class, context);
if (binding.getHandlerChain() == null || binding.getHandlerChain().isEmpty()) {
// no handlers so let's just directly invoke the bean
log.debug("No handlers found.");
EjbMethodInvoker invoker = (EjbMethodInvoker) service.getInvoker();
return invoker.directEjbInvoke(this.exchange, this.method, this.params);
} else {
// have handlers so have to run handlers now and redo data binding
// as handlers can change the soap message
log.debug("Handlers found.");
Message inMessage = exchange.getInMessage();
PhaseInterceptorChain chain = new PhaseInterceptorChain(bus.getExtension(PhaseManager.class).getInPhases());
chain.setFaultObserver(endpoint.getOutFaultObserver());
/*
* Since we have to re-do data binding and the XMLStreamReader
* contents are already consumed by prior data binding step
* we have to reinitialize the XMLStreamReader from the SOAPMessage
* created by SAAJInInterceptor.
*/
if (inMessage instanceof SoapMessage) {
try {
reserialize((SoapMessage) inMessage);
} catch (Exception e) {
throw new ServerRuntimeException("Failed to reserialize soap message", e);
}
} else {
// TODO: how to handle XML/HTTP binding?
}
this.exchange.setOutMessage(null);
// install default interceptors
chain.add(new ServiceInvokerInterceptor());
//chain.add(new OutgoingChainInterceptor()); // it is already in the enclosing chain, if we add it there we are in the tx so we write the message in the tx!
// See http://cwiki.apache.org/CXF20DOC/interceptors.html
// install Holder and Wrapper interceptors
chain.add(new WrapperClassInInterceptor());
chain.add(new HolderInInterceptor());
// install interceptors for handler processing
chain.add(new MustUnderstandInterceptor());
chain.add(new LogicalHandlerInInterceptor(binding));
chain.add(new SOAPHandlerInterceptor(binding));
// install data binding interceptors - todo: check we need it
copyDataBindingInterceptors(chain, inMessage.getInterceptorChain());
InterceptorChain oldChain = inMessage.getInterceptorChain();
inMessage.setInterceptorChain(chain);
try {
chain.doIntercept(inMessage);
} finally {
inMessage.setInterceptorChain(oldChain);
}
// TODO: the result should be deserialized from SOAPMessage
Object result = getResult();
return result;
}
}Example 24
| Project: cxf-circuit-switcher-master File: CircuitSwitcherTargetSelectorTest.java View source code |
@Test
public void shouldRequireFailoverWhereIOExceptionHasBeenThrown() {
circuitBreakerTargetSelector = new CircuitSwitcherTargetSelector(null, 0, 0, null);
Exchange exchange = new ExchangeImpl();
Message message = new SoapMessage(Soap11.getInstance());
exchange.setOutMessage(message);
message.put(Exception.class, new IOException());
boolean requiresFailover = circuitBreakerTargetSelector.requiresFailover(exchange);
assertTrue(requiresFailover);
}Example 25
| Project: mule-camunda-24-master File: InInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage message) throws Fault {
// Called before service method is executed.
txHandler.beginTransaction();
}Example 26
| Project: juddi-master File: XMLDeclarationWritingInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage message) throws Fault {
message.put("org.apache.cxf.stax.force-start-document", Boolean.TRUE);
}Example 27
| Project: xcmis-master File: UserContextInterceptor.java View source code |
/**
* {@inheritDoc}
*/
public void handleMessage(SoapMessage message) throws Fault {
UserContext ctx = new UserContext(principal);
UserContext.setCurrent(ctx);
}Example 28
| Project: linshare-core-master File: SoapExceptionInterceptor.java View source code |
@Override
public void handleMessage(SoapMessage message) throws Fault {
Fault fault = (Fault) message.getContent(Exception.class);
Throwable ex = fault.getCause();
if (ex instanceof BusinessException) {
BusinessException e = (BusinessException) ex;
generateSoapFault(fault, e);
}
}