Add wsse:UsernameToken in soap header - java

I am working on SOAP client. My WSDL URL is http://localhost:8080/soap/getMessage?wsdl.
This requires the the following header to specify the username and password.
<wsdl:Envelope xmlns:soap="..."
xmlns:wsse="..." >
<wsdl:Header>
<wsse:Security>
<wsse:UsernameToken>
<wsse:Username>admin</wsse:Username>
<wsse:Password>password</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</wsdl:Header>
</wsdl:Envelope>
I have to write a program for it.
Can some one help me.
Thanks.

here is my past program for soap. I already modified it to your case.
//create SOAP
SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
SOAPConnection connection = sfc.createConnection();
SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
SOAPBody soapBody = soapEnvelope.getBody();
SOAPElement Header = soapBody.addBodyElement(new QName("Header"));
//attribute
SOAPElement Security= Header.addChildElement(new QName("Security"));
SOAPElement UsernameToken= Security.addChildElement(new QName("UsernameToken"));
SOAPElement Username= UsernameToken.addChildElement(new QName("Username"));
SOAPElement Password= UsernameToken.addChildElement(new QName("Password"));
//enter the username and password
Username.addTextNode("username");
Password.addTextNode("password");
//send the soap and print out the result
URL endpoint = "http://localhost:8080/soap/getMessage?wsdl";
SOAPMessage response = connection.call(soapMessage, endpoint);
ByteArrayOutputStream out = new ByteArrayOutputStream();
String xml = "";
try {
response.writeTo(out);
xml = out.toString("UTF-8");
} catch (Exception e)
{
System.out.println(""+e);
//log.error(e.getMessage(),e);
}
System.out.println(""+xml);
for further information you can search the google for using SOAP in JDK 1.6

Related

How do i send the file with "soap" in java

I'm trying to send files with soap. but somehow I failed. Help me please gave me the codes below and the error I received.
public void SendTest() {
try {
String filePath = "C:/test/fb344a10-713a-4e45-8810-6a82237947af.zip";
String host = "https://test.efatura.gov.tr/earsiv/services/EArsivWsPort?wsdl";
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
java.net.URL endpoint = new URL(host);
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
soapEnvelope.addNamespaceDeclaration("EArsivWsService", "http://earsiv.vedop3.ggm.gov.org/");
SOAPHeader header = message.getSOAPHeader();
SOAPBody body = message.getSOAPBody();
// QName qNameMethod=new QName("","sendDocumentFile","tns");
// SOAPBodyElement bodyElement = (SOAPBodyElement)
// body.addChildElement(qNameMethod);
SOAPFactory soapFactory = SOAPFactory.newInstance();
Name bodyName = soapFactory.createName("http://earsiv.vedop3.ggm.gov.org/", "tns", "sendDocumentFile");
body.addChildElement(new QName("name","fb344a10-713a-4e45-8810-6a82237947af.zip"));
URL url = new File(filePath).toURI().toURL();
DataHandler dataHandler = new DataHandler(url);
AttachmentPart attachment = message.createAttachmentPart(dataHandler);
// attachment.setContentId("");
message.addAttachmentPart(attachment);
message.saveChanges();
SOAPMessage response = connection.call(message, endpoint);
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(8192);
response.writeTo(bOutput);
String strResponse = bOutput.toString();// TODO use encoding for turkish
System.out.println(strResponse);
} catch (SOAPException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Error response:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode xmlns:ns1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">ns1:InvalidSecurity</faultcode>
<faultstring>An error was discovered processing the <wsse:Security> header</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
SOAP message should be signed with Wss

is there a way for me to pass this soap request as a xml in java?

POST /webservices/producao/cdc/cdc.asmx HTTP/1.1
Host: www.soawebservices.com.br
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "SOAWebServices/PessoaFisicaSimplificada"
<?xml version="1.0" encoding="utf-8"?>
soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"/
soap:Body
<PessoaFisicaSimplificada xmlns="SOAWebServices">
<Credenciais>
<Email>string</Email>
<Senha>string</Senha>
</Credenciais>
<Documento>string</Documento>
<DataNascimento>string</DataNascimento>
</PessoaFisicaSimplificada>
/soap:Body
/soap:Envelope
i have this code i been trying to build:
public void start(){
try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
String url = "www.soawebservices.com.br";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
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();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "SOAWebServices/PessoaFisicaSimplificada";
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("soap", serverURI);
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("PessoaFisicaSimplificada", "","SOAWebServices");
SOAPElement soapBodyElemC = soapBodyElem.addChildElement("Credenciais");
SOAPElement soapBodyElem1 = soapBodyElemC.addChildElement("Email");
soapBodyElem1.addTextNode("EMAIL");
SOAPElement soapBodyElem2 = soapBodyElemC.addChildElement("Senha");
soapBodyElem2.addTextNode("PASSWORD");
SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("Documento");
soapBodyElem3.addTextNode("CPF");
SOAPElement soapBodyElem4 = soapBodyElem.addChildElement("DataNascimento");
soapBodyElem4.addTextNode("Date");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI);
soapMessage.saveChanges();
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
however it throws: (javax.xml.soap.SOAPException: JBWS024004: SOAP message could not be sent), i'd guess it's either the uri or the url that i'm passing wrong or i'm not creating the header correctly
the current request it's producing:
SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap="SOAWebServices/PessoaFisicaSimplificada"
SOAP-ENV:Header/
SOAP-ENV:Body
<PessoaFisicaSimplificada xmlns="SOAWebServices">
<Credenciais>
<Email>EMAIL</Email>
<Senha>PASSWORD</Senha>
</Credenciais>
<Documento>CPF</Documento>
<DataNascimento>Date</DataNascimento>
</PessoaFisicaSimplificada>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Ok, it seems you are not providing SOAP Endpoint correctly.
Find below working code. Have just specified full SOAP Endpoint.
public static void main(String[] args) {
try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
String url = "http://www.soawebservices.com.br/webservices/producao/cdc/cdc.asmx";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
soapResponse.writeTo(System.out);
//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();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "SOAWebServices/PessoaFisicaSimplificada";
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("soap", serverURI);
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("PessoaFisicaSimplificada", "","SOAWebServices");
SOAPElement soapBodyElemC = soapBodyElem.addChildElement("Credenciais");
SOAPElement soapBodyElem1 = soapBodyElemC.addChildElement("Email");
soapBodyElem1.addTextNode("EMAIL");
SOAPElement soapBodyElem2 = soapBodyElemC.addChildElement("Senha");
soapBodyElem2.addTextNode("PASSWORD");
SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("Documento");
soapBodyElem3.addTextNode("CPF");
SOAPElement soapBodyElem4 = soapBodyElem.addChildElement("DataNascimento");
soapBodyElem4.addTextNode("Date");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI);
soapMessage.saveChanges();
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}

How do I make a java client to call a soap WebService method with parameters?

How do I make a java client to call a soap WebService method with parameters?
I've tried this class for a java client
import javax.xml.soap.*;
public class SOAPClientSAAJ {
public static void main(String args[]) throws Exception {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http:localhost:8080/myproject/mywebservice?wsdl";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// print SOAP Response
System.out.print("Response SOAP Message:");
soapResponse.writeTo(System.out);
soapConnection.close();
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String namespace= "http://wsnamespace/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", namespace);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("Login", "example");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("username", "example");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("password", "example");
soapBodyElem1.addTextNode("email#example.com");
soapBodyElem2.addTextNode("1234");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", namespace + "Login");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
}
with this java webservice method
#WebMethod(operationName="Login")
public boolean Login(#WebParam(name = "username") String username,
#WebParam(name = "password") String password) {
System.out.print(username + "-" + password);
}
but username and password are always null so the output when the method is called is "null-null", I would like to know how call this method sending the paramaters correctly.
thanks!
You can make a HTTPClient call and pass SOAP request as string parameter.
There are better way to do this that internally does the above for example using Apache AXIS2, CXF, JAX-WS etc.
I prefer to use CXF by generating stubs of WSDL file and calling the service through JAVA.
Refer examples:
https://rathinasaba.wordpress.com/2013/02/01/call-webservice-wsdl-based-using-apache-httpconnection/
How to call a SOAP webservice with a simple String (xml in string format)

Calling a soap webservice from java with nonce in security headers

I am trying to call a webservice from java. This is basically not that difficult, except that the webservice expects some security in the form of a username and password and a nonce.
When I try to call the webservice from SoapUi, I see that the raw message looks like this:
<soapenv:Envelope xmlns:sch="http://somedomain.com/pe/ws/schema"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<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"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-E70691ACBDEFEC750814238295617871">
<wsse:Username>usr</wsse:Username>
<wsse:Password
Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"
>pw</wsse:Password>
<wsse:Nonce
EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
>4smQZF5KMSktEXrQc0v5yw==</wsse:Nonce>
<wsu:Created>2015-02-13T12:12:41.784Z</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<sch:EventSubmitRequest>
<sch:Event>
<sch:EventId>392</sch:EventId>
<sch:Recoverable>false</sch:Recoverable>
</sch:Event>
</sch:EventSubmitRequest>
</soapenv:Body>
</soapenv:Envelope>
The obvious elements in the message are the Username, Password and Created, but what puzzles me is the nonce. In the example this field has the value 4smQZF5KMSktEXrQc0v5yw==, but this value difference upon each request (which makes sense, since according to wikipedia, a nonce is an arbitrary number used only once). When searching around, I can't find any usable examples of how to generate the nonce in java (Although I did find some php examples here on stack overflow, but I can't easily verify weather they work) . While I don't mind construction this nonce myself, I'm wondering if this is really necessary, I kind of would expect this to be standard functionality in java.
Below is the code I'm using:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class soaptest {
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://142.10.10.52:8080/pe/ws/pe/";
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();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = soapMessage.getSOAPHeader();
SOAPElement security = header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
SOAPElement usernameToken = security.addChildElement("UsernameToken", "wsse");
usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
SOAPElement username = usernameToken.addChildElement("Username", "wsse");
username.addTextNode("usr");
SOAPElement password = usernameToken.addChildElement("Password", "wsse");
password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
password.addTextNode("pw");
SOAPElement nonce = usernameToken.addChildElement("Nonce", "wsse");
nonce.setAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
nonce.addTextNode("???");
SOAPElement created = usernameToken.addChildElement("Created", "wsse");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Calendar c1 = Calendar.getInstance();
created.addTextNode(sdf.format(c1.getTime()));
String serverURI = "http://somedomain.com/pe/ws/schema";
envelope.addNamespaceDeclaration("sch", serverURI);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("EventSubmitRequest", "sch");
SOAPElement soapBodyElem1 = soapBody.addChildElement("Event", "sch");
soapBodyElem.addChildElement(soapBodyElem1);
SOAPElement soapBodyElem2 = soapBodyElem1.addChildElement("EventId", "sch");
soapBodyElem2.addTextNode("392");
SOAPElement soapBodyElem3 = soapBodyElem1.addChildElement("Recoverable", "sch");
soapBodyElem3.addTextNode("false");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "EventSubmitRequest");
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);
}
}
The Oasis reference for the UsernameToken helped me fill in some of the blanks. Pages 7,8,9 are most appropriate in this case. In particular these sections
/wsse:UsernameToken/wsse:Nonce
This optional element specifies a cryptographically random nonce. Each message
including a element MUST use a new nonce value in order for web
service producers to detect replay attacks.
and
/wsse:UsernameToken/wsse:Nonce/#EncodingType
This optional attribute URI specifies the encoding type of the nonce (see the definition of
<wsse:BinarySecurityToken> for valid values). If this attribute isn't specified then
the default of Base64 encoding is used.
In regards to generating the 'cryptographically random' nonce, can suggest you use this answer and then create an encoded string from it. Base64 encoding in your case, as that is the encodingType you are using in your XML request above.
For Spring WS users: check securityPolicy.xml contains line
<xwss:RequireUsernameToken passwordDigestRequired="false" nonceRequired="true" />
It fixes exception Receiver Requirement for nonce has not been met for SoapUi.
In case there is no "nonce" in request, set
nonceRequired="false"

Java version of SoapClient

I have a working soaprequest in PhP and i'm trying to create a java program that requires the same call, However i am really struggeling to find the way to create the below php code in java, i have found numerus websites explaining soap requests in java but i cant seem to work how how to send the $param_auth array.
Any help would be most appreciated as i've been stuck on this for a while.
Thanks in advance.
$param_auth=array(
'user'=>$username,
'id'=>$userID,
'message'=>$userMessage
);
$soapclient = new soapclient(WebsiteAddress);
$data->_db = $soapclient->call('uploadMessage',$param_auth);
Finally solved my issue (Ive changed Element names etc.), using eclipse shows you the Soap envelope and XML response which i found useful for debugging the envelope).
Hope this helps anyone trying to do similar.
The "UploadMessage" is the "Login" string and the
$param_auth=array(
'user'=>$username,
'id'=>$userID,
'message'=>$userMessage
);
is the Username and Password, (Left out the Message part).
This code sends an Envelope like this the server:-
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:Login="Your URL"><SOAP-ENV:Header/><SOAP-ENV:Body><Login><UserName>YourUserName</UserName><Password>YourPassword</Password></Login></SOAP-ENV:Body></SOAP-ENV:Envelope>
Code To create the above Envelope is below:-
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class SoapCall {
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server.
String url = "Your URL";
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 {
String YourUsername = "UserName";
String YourPassword = "Password";
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "Your URL";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("Login", serverURI);
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("Login");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("UserName");
soapBodyElem2.addTextNode(YourUserName);
SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("Password");
soapBodyElem3.addTextNode(YourPassword);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "Login");
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);
}
}

Categories