Retrieving credentials from SOAP header - web-services

This a sample SOAP request I'm sending to a WS which is deployed in WAS 8.5
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://xmlns.scania.com/logistics/schema/transport/v1">
<soapenv:Header>
<wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-37" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>username</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">
password
</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<v1:TransportInformationRequest>
<!--1 or more repetitions:-->
<v1:ChassisNumber>2105909</v1:ChassisNumber>
</v1:TransportInformationRequest>
</soapenv:Body>
</soapenv:Envelope>
What I want is to retrieve the username and password sent in the above request. I flipped through the Java EE api but couldn't find the correct way to do the same. I have written a painful code in the SOAPHandler as below :
#Override
public boolean handleMessage(SOAPMessageContext context) {
// TODO Auto-generated method stub
Boolean isOutbound = (Boolean) context
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
log.info("In TransportHandler.handleMessage(...) " + isOutbound);
if (!isOutbound) {
SOAPMessage soapMsg = context.getMessage();
SOAPEnvelope soapEnv;
try {
soapEnv = soapMsg.getSOAPPart().getEnvelope();
SOAPHeader soapHeader = soapEnv.getHeader();
Iterator<SOAPElement> securityHeaderElements = soapHeader
.getChildElements(new QName(
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
"Security", "wsse"));
if (securityHeaderElements.hasNext()) {
SOAPElement securityHeaderElement = securityHeaderElements
.next();
log.info("*****securityHeaderElement : "
+ securityHeaderElement + " type is "
+ securityHeaderElement.getClass().getName());
Iterator<Node> securityHeaderChildren = securityHeaderElement
.getChildElements();
while (securityHeaderChildren.hasNext()) {
Node securityElement = securityHeaderChildren.next();
log.info("*****securityElement : "
+ securityElement.getClass().getName());
if (securityElement instanceof com.ibm.ws.webservices.engine.xmlsoap.SOAPElement) {
com.ibm.ws.webservices.engine.xmlsoap.SOAPElement securitySOAPElement = (com.ibm.ws.webservices.engine.xmlsoap.SOAPElement) securityElement;
log.info("*****securitySOAPElement "
+ securitySOAPElement);
Iterator<Node> securitySOAPElementChildren = securitySOAPElement
.getChildElements();
while (securitySOAPElementChildren.hasNext()) {
Node securitySOAPElementChild = securitySOAPElementChildren
.next();
log.info("*****securitySOAPElementChild : "
+ securitySOAPElementChild);
if (securitySOAPElementChild instanceof com.ibm.ws.webservices.engine.xmlsoap.SOAPElement) {
com.ibm.ws.webservices.engine.xmlsoap.SOAPElement securitySOAPChildElement = (com.ibm.ws.webservices.engine.xmlsoap.SOAPElement) securitySOAPElementChild;
log.info("*****securitySOAPChildElement "
+ securitySOAPChildElement);
}
}
}
}
}
} catch (SOAPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
log.info("Returning from TransportHandler.handleMessage(...)");
return true;
}
What is the efficient way to get the username and password ?

Related

invoking wsdl operations through c#

I need to create a win forms app in VS 2013, which will take a wsdl file as a webReference. It will invoke an wsdl:operation "Init" which will send the following xml to the web service :
The Wsdl contains the operation:
<wsdl:operation name="Init">
<wsdl:input message="wl:InitRequest"/>
<wsdl:output message="wl:InitResponse"/>
</wsdl:operation>
The Init SOAP xml
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.asdfgh.org/lala/log">
<soapenv:Header/>
<soapenv:Body>
<web:Init>
<web:Phase>`TST`</web:Phase>
</web:Init>
</soapenv:Body>
</soapenv:Envelope>
It will send a response back InitResponse:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.asdfgh.org/lala/log">
<soapenv:Header/>
<soapenv:Body>
<wl:InitResponse xmlns:wl="http://www.asdfgh.org/lala/log">
<Data>
<NUMBER>1234</NUMBER>
<TEXT1>ABCDEF</TEXT1>
<TEXT2>QWERTY</TEXT2>
</Data>
</wl:InitResponse>
</soapenv:Body>
</soapenv:Envelope>
How to I read the response back and show the ouput in a MessageBox.Show();
Below is the class formed by the wsdl on the Init.
public partial class Init {
private string phaseField;
/// <remarks/>
public string Phase {
get {
return this.phaseField;
}
set {
this.phaseField = value;
}
}
}
Below is the class formed by the wsdl on InitResponse(funny thing is, it did not create any class named InitResponse. It has created InitResponseData -- I wonder why)
public partial class InitDSDResponseData {
private string NUMBERField;
private string TEXT1Field;
private string TEXT2Field;
/// <remarks/>
public string NUMBER {
get {
return this.NUMBERField;
}
set {
this.NUMBERField = value;
}
}
/// <remarks/>
public string TEXT1 {
get {
return this.TEXT1Field;
}
set {
this.TEXT1Field = value;
}
}
/// <remarks/>
public string TEXT2 {
get {
return this.TEXT2Field;
}
set {
this.TEXT2Field = value;
}
}
}
On a button click event, I want to show the response xml in a Message Box as a string. How should I proceed? How do I invoke the Init operation through c#?

How to call web service to achieve login system in Android?

i have a xml project. this is the Login sample code
http://10.99.99.99:8087/item/services/ItemService
<soapenv:Header/>
<soapenv:Body>
<ser:userLogin>
<!--Optional:-->
<arg0>admin</arg0>
<!--Optional:-->
<arg1>admin</arg1>
</ser:userLogin>
</soapenv:Body>
</soapenv:Envelope>
If Succeed
<soap:Body>
<ns2:userLoginResponse xmlns:ns2="http://services.ws.item/">
<return>
<result>1</result>
<msg>Login Succeed</msg>
</return>
</ns2:userLoginResponse>
</soap:Body>
</soap:Envelope>
If Not Succeed
<soap:Body>
<ns2:userLoginResponse xmlns:ns2="http://services.ws.item/">
<return>
<result>-1</result>
<msg>Login failed</msg>
</return>
</ns2:userLoginResponse>
</soap:Body>
</soap:Envelope>
the service will connect to MySQL server.
i change the test code, but it still cannot run, and i am so sure the wsdl is work. the logcat shows a lot of error.
public class CheckLoginActivity extends Activity {
private static final String SOAP_ACTION = "http://services.ws.item/userLogin";
private static final String METHOD_NAME = "userLogin";
private static final String NAMESPACE = "http://services.ws.item/";
private static final String URL = "http://10.99.99.99:8087/item/services/ItemService?wsdl";
private TextView tv;
private String response;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv= (TextView)findViewById(R.id.tv1);
myAsyncTask myRequest = new myAsyncTask();
myRequest.execute();
}
private class myAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// tv.setText(response);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("arg0", "admin");
request.addProperty("arg1", "admin");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(URL);
httpTransport.debug = true;
try {
httpTransport.call(SOAP_ACTION, envelope);
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //send request
SoapPrimitive result;
try {
result = (SoapPrimitive) envelope.getResponse();
Log.d("App",""+result.toString());
response = result.toString();
} catch (SoapFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}

Issue invoking web service within websphere 6.1 environment

I'm trying to invoke a SOAP web service from within WebSphere 6.1. I can run the code fine using Apache Tomcat 6.0.36 runtime. However, with WebSphere 6.1, I get the following error:
Jan 5, 2015 7:19:23 PM com.ibm.ws.ssl.config.SSLConfigManager INFO:ssl.disable.url.hostname.verification.CWPKI0027I
Jan 5, 2015 7:19:24 PM com.ibm.ws.channel.framework.impl.WSChannelFrameworkImpl AUDIT: chain.started
Jan 5, 2015 7:19:25 PM com.ibm.ws.webservices.engine.PivotHandlerWrapper invoke WARNING:
WSWS3734W: Warning: Exception caught from invocation to com.ibm.ws.webservices.engine.transport.http.HTTPSender:
WebServicesFault faultCode:
HTTP faultString: ( 401 ) Unauthorized faultActor: http://server.customer.com:80
faultDetail: null:
WSWS3192E: Error: return code: ( 401 ) Unauthorized
Here's the code I'm running, which works fine in Apache Tomcat:
public class Test {
public void submitOrder()
{
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://server.customer.com/serviceEndpoint";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
MimeHeaders hd = soapMessage.getMimeHeaders();
String username = "xxxxx";
String password = "xxxxx";
byte [] auth = (username+":"+password).getBytes();
String authorization = new String ( Base64.encodeBase64(auth) );
System.out.println ( "authorization = " + authorization );
hd.addHeader("Authorization", "Basic " + authorization);
SOAPPart soapPart = soapMessage.getSOAPPart();
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement ordersElem = soapBody.addChildElement("Orders");
// Need to add two attributes to this node!
SOAPElement orderElem = ordersElem.addChildElement("Order");
Name codeAttributeName = envelope.createName("code");
orderElem.addAttribute(codeAttributeName, "00001");
Name timeAttributeName = envelope.createName("time");
orderElem.addAttribute(timeAttributeName, "2015-01-04 12:00:00 PM");
SOAPElement salesOrderConfElem = orderElem.addChildElement("SalesOrderConfirmationCode");
salesOrderConfElem.addTextNode("16041");
SOAPElement statusElem = orderElem.addChildElement("Status");
Name statusCodeAttributeName = envelope.createName("code");
statusElem.addAttribute(statusCodeAttributeName, "COMPLETE");
SOAPElement entriesElem = orderElem.addChildElement("Entries");
SOAPElement entryElem = entriesElem.addChildElement("Entry");
SOAPElement entryNumElem = entryElem.addChildElement("EntryNumber");
entryNumElem.addTextNode("1");
SOAPElement productElem = entryElem.addChildElement("ProductCode");
productElem.addTextNode("738053571");
SOAPElement qtyElem = entryElem.addChildElement("Quantity");
qtyElem.addTextNode("1");
SOAPElement shippedElem = entryElem.addChildElement("Shipped");
shippedElem.addTextNode("1");
SOAPElement backOrderElem = entryElem.addChildElement("Backordered");
backOrderElem.addTextNode("1");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", "http://sap.com/xi/WebService/soap1.1");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
/**
* #param args
*/
public static void main(String[] args) {
Test t = new Test();
t.submitOrder();
}
}
CORRECTION: the SOAP envelopes being created by Tomcat and WebSphere are not the same. Tomcat, using Java 1.6, creates the following:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<Orders>
while WebSphere, using IBM's version of 1.5, creates the following:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header/>
<soapenv:Body>
<Orders>
How would I get WebSphere to create the same SOAP envelop as Tomcat?

SOAP call to a webservice with Talend for ESB and SOAPUI

I query to a webservice with this operation:
public schema.cupservices.Output callService(
#WebParam(partName = "inputMessage", name = "inputMessage", targetNamespace = "http://schema/cupServices") schema.cupservices.Input inputMessage);
inputMessage is of a type "Input":
public abstract class Input {
#XmlElement(required = true)
protected LoginData loginData;
public LoginData getLoginData() {
return loginData;
}
public void setLoginData(LoginData value) {
this.loginData = value;
}
}
when I try to call the service on Talend using the TSOAP component and with SOAPUI, both take as input:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:cup="http://schema/cupServices">
<soapenv:Header/>
<soapenv:Body>
<cup:inputMessage>
<cup:loginData>
<cup:username>user</cup:username>
<cup:password>123</cup:password>
</cup:loginData>
</cup:inputMessage>
</soapenv:Body>
</soapenv:Envelope>
I get this error:
<S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
<faultcode>S:Server</faultcode>
<faultstring>javax.xml.bind.UnmarshalException
- with linked exception:
[javax.xml.bind.UnmarshalException: Unable to create an instance of schema.cupservices.Input
- with linked exception:
[java.lang.InstantiationException]]</faultstring>
I know that Input is an abstract class, but the wsdl of the webservice is set in this way...
How can I resolve this problem?
Thanks

Customize SOAP request send from Windows 8 application

I am consuming a WSDL in a Windows 8 app. I need to customize the SOAP request like
New SOAP Request:
</ns0:Header>
<ns0:Body>
<ns0:Request xmlns:ns0="http://www.ABC.co.il/2004/01/RetrieveEntityDetails/EntityDetailsRequest">
</ns0:Request></ns0:Body></ns0:Envelope>
Current SOAP Request:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
</s:Header>
<s:Body>
<RetrieveEntityDetailsXPOP_XmlRequest xmlns="http://tempuri.org/">
<RetrieveEntityDetailsXPOP_Xml xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<requestDoc>
</requestDoc>
</RetrieveEntityDetailsXPOP_Xml>
</RetrieveEntityDetailsXPOP_XmlRequest>
</s:Body>
</s:Envelope>
How will I change the namespace and set a request tag inside the body tag.
Code:
Client = new EAI_RetrieveEntityDetailsXP_ServiceSoapClient();
Client.RetrieveEntityDetailsXPOP_XmlCompleted += Client_RetrieveEntityDetailsXPOP_XmlCompleted;
XElement requestData = GetRequestData();
using (new OperationContextScope(Client.InnerChannel))
{
// Create a custom soap header
var msgHeader = MessageHeader.CreateHeader("myCustomHeader", string.Empty, "myValue");
// Add the header into request message
OperationContext.Current.OutgoingMessageHeaders.Add(msgHeader);
Client.RetrieveEntityDetailsXPOP_XmlAsync(requestData);
}
I have actually used HttpCleint to call this service by using following code. Using this we can generate the SOAP request as desired.
string soapString = ConstructSoapRequest();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("SOAPAction", SOAPActionUri);
var content = new StringContent(soapString, Encoding.UTF8, "text/xml");
using (var response = await client.PostAsync(Uri, content))
{
var soapResponse = await response.Content.ReadAsStringAsync();
return soapResponse;
}
}
private string ConstructSoapRequest()
{
return String.Format(#"<ns0:Envelope xmlns:ns0='http://www.cellcom.co.il/2004/01/std-headers'>
<ns0:Header>
</ns0:Header>
<ns0:Body>
<ns0:Request xmlns:ns0='http://www.cellcom.co.il/2004/01/RetrieveEntityDetails/EntityDetailsRequest'>
</ns0:Request></ns0:Body></ns0:Envelope>", 100);
}