JAX-WS Authentication SoapUI vs. Client application - security

I need to create an SOAP client with JAX-WS on JBoss.
The Problem is I cannot get past the authentication.
I have a test implemented in SoapUI which works when I set the request properties username and password
With the following code
URL kbaURL = new URL("http://...");
IkfzService ikfzService = new IkfzService(kbaURL);
IkfzPortType ikfzPortType = ikfzService.getIkfzSOAP();
Map<String, Object> requestContext = ((BindingProvider)ikfzPortType).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, "...");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "...");
Where URL, username und password are the same like in SOAPUI I am getting
javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException:
Failed to create service.
...
Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR:
Problem parsing 'http://..'.: java.io.IOException: Server returned HTTP response code:
401 for URL: http://..
What am I missing?

This should be a basic example of what you're trying to accomplish - let me know if you need more help or clarification
//the WSDL/webservice endpoint
private static final String WSDL_URL = "http://localhost:8080/MyWebService/MyWebService?wsdl";
URL url = new URL(WSDL_URL);
QName qname = new QName("http://ws.mycompany.com/", MyWebServiceImpl");
Service theWSService = Service.create(url, qname);
//returns the interface for MyWebServiceImpl
TheWSServiceIF port = theWSService.getPort(TheWSServiceIF.class);
//Setup Security
Map<String, Object> requestContext = ((BindingProvider)port).getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>();
requestHeaders.put("Username", Collections.singletonList("myUserName"));
requestHeaders.put("Password", Collections.singletonList("myPasword"));
requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
/**********************************************************************/
//actually call the web service method, print results
System.out.println(port.getMyWebServiceData());

Related

REST Api is not returning expected data

I wrote an Auth API where it should retrieve the details from my user, but I'm getting error 404 instead. All my users are stored in an Azure Storage Account, and I was using the TableClient class to handle with my table. However I am not able to go any further when I started to do this Auth. I spent over one week only on this function, and I got no progress on this, here is my code:
[FunctionName(nameof(Auth))]
public static async Task<IActionResult> Auth(
[HttpTrigger(AuthorizationLevel.Admin, "POST", Route = "auth")] HttpRequest req,
[Table("User", Connection = "AzureWebJobsStorage")] TableClient tdClient,
ILogger log)
{
string url = String.Format("http://localhost:7235/api/");
HttpMessageHandler handler = new HttpClientHandler()
{
};
var httpClient = new HttpClient(handler)
{
BaseAddress = new Uri(url),
Timeout = new TimeSpan(0, 2, 0)
};
httpClient.DefaultRequestHeaders.Add("ContentType", "application/json");
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("roy.mitchel#somecompany.com:pass1234");
string val = System.Convert.ToBase64String(plainTextBytes);
httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + val);
HttpResponseMessage response = httpClient.GetAsync(url).Result;
return new OkObjectResult(response);
}
How can auth my user using this class? Iam doing on the right way?
Thanks.
Debugging any API issues by looking at just the code, is (as you have discovered) a horribly painful process.
I'd strongly recommend using a MITM proxy (like burp) to get visibility of exactly what is sent to, and received from the API. By using this approach, it generally becomes really obvious what is wrong.
If you can't use this approach, then enable logging for the raw HTTP request and response, as outlined in this guide.

HTTP :connect timeout and read timeout for URLStreamHandler with SAAJ working for windows but not working on linux sytem

I'm a beginner when it comes to HTTP connections.
Currently i'm working with SAAJ api to have my soap based client, where to handle timeouts i ended up using URLStreamHandler for HTTP connection properties with the endpoints.
Problem is that this timeout works for my windows based system, however it isn't working for the Linux server it is going to go live on.
below is the code for fetching endpoint with set properties. It is a HTTP POST connection.
URL endpoint = new URL (null, url, new URLStreamHandler () {
protected URLConnection openConnection (URL url) throws IOException {
// The url is the parent of this stream handler, so must create clone
URL clone = new URL (url.toString ());
HttpURLConnection connection = (HttpURLConnection) clone.openConnection();
connection.setRequestProperty("Content-Type",
"text/xml");
connection.setRequestProperty("Accept",
"application/soap+xml, text/*");
// If we cast to HttpURLConnection, we can set redirects
// connection.setInstanceFollowRedirects (false);
connection.setDoOutput(true);
connection.setConnectTimeout(3 * 1000);
connection.setReadTimeout(3 * 1000);
return connection;
for the SAAJ API part, below is the implementation, pretty basic one
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory
.newInstance();
soapConnection = soapConnectionFactory.createConnection();
is = new ByteArrayInputStream(command.getBytes());
SOAPMessage request = MessageFactory.newInstance(
SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(
new MimeHeaders(), is);
MimeHeaders headers = request.getMimeHeaders();
headers.addHeader("Content-Type", "text/xml");
request.saveChanges();
ByteArrayOutputStream out = new ByteArrayOutputStream();
request.writeTo(out);
soapResponse = soapConnection.call(request, endpoint);
Is it that system properties would affect connect or read timeout. If so please let me know what could cause this behavior.

Vimeo API - Get public video details using access token

I need to get public information about Vimeo Video. I want to use the vimeo-php code from Vimeo, I have created my App, with credentials and access-token, but I cannot find a way to use them.
When I ask for:
https://api.vimeo.com/videos/{video_id}/access_token={access_token}
I got the error: you must provide an authenticated access token.
Someone can explain me how to make a call correctly?
When you read the documentation notice you have to add the Authorization header to your request. Please read https://developer.vimeo.com/api/authentication#making-requests.
You can get video using retrofit too.
String BASE_URL = "https://api.vimeo.com/";//For Retrofit client object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
#GET("/videos/{videoId}")
Call<MyVideoResponse> getPrivateVimeoVideo(#HeaderMap Map<String, String>
headers, #Path("videoId") String videoId);
Then you can call like this...
String accessToken = "1a1e1ec3***************";
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + accessToken);
headers.put("Accept", "application/vnd.vimeo.*+json;version=3.2");
String videoId = "309065...";`enter code here`
RetrofitClient.create(ApiInterface.class).getPrivateVimeoVideo(headers,
videoId).enqueue(new CallBack<MyVideoResponse>(){...........}

ServiceStack - Switch off Snapshot

I've followed instructions on how creating a ServiceStack here at:
https://github.com/ServiceStack/ServiceStack/wiki/Create-your-first-webservice
I'm sure I have followed it to the letter, but as soon as I run the web application. I get a 'Snapshot' view of my response. I understand this happens when I don't have a default view/webpage. I set up the project as a ASP.net website, not a ASP.net MVC website. Could that be the problem?
I also wrote a test console application with the following C# code. It got the response as a HTML webpage rather than as a plain string e.g. "Hello, John".
static void sendHello()
{
string contents = "john";
string url = "http://localhost:51450/hello/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = contents.Length;
request.ContentType = "application/x-www-form-urlencoded";
// SEND TO WEBSERVICE
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(contents);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
}
How can I switch off the 'snapshot' view? What am I doing wrong?
The browser is requesting html so ServiceStack is returning the html snapshot.
There are a couple of ways to stop the snapshot view:
First is to use the ServiceClient classes provided by servicestack. These also have the advantage of doing automatic routing and strongly typing the response DTOs.
Next way would be to set the Accept header of the request to something like application/json or application/xml which would serialize the response into json or xml respectively. This is what the ServiceClients do internally
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
...
Another method would be to add a query string parameter called format and set it to json or xml
string url = "http://localhost:51450/hello/?format=json";
Putting the specific format requesting is the practical way to do this
string url = "http://localhost:51450/hello/?format=json";
I suggest simply deleting this feature.
public override void Configure(Container container)
{
//...
this.Plugins.RemoveAll(p => p is ServiceStack.Formats.HtmlFormat);
//...
}
Now all requests with the Content-Type=text/html will be ignored.

Prevent RestSharp changing https to http

I have a very simple piece of code using v130 of RestSharp. The code itself compiles fine and returns values from the server - the problem is they're not the ones I'm after.
Code
private void startTest()
{
string email = "bob2#example.com";
string password = "password";
doRestSharpWebRequest(email, password);
}
private void doRestSharpWebRequest(email, password)
{
var restClient = new RestClient();
restClient.BaseUrl = "https://mytestserver.com/api";
restClient.Authenticator = new SimpleAuthenticator("email", email, "password", password);
var restRequest = new RestRequest("token", Method.GET);
restRequest.AddHeader("Accepts", "application/json;version=1");
restRequest.AddHeader("Authorization", "apikey zyzyz");
restRequest.RequestFormat = DataFormat.Json;
IRestResponse<userlogin> response = restClient.Execute<userlogin>(restRequest);
}
where userlogin is just a class to deserialize to.
When I run the code, I'm presented with the following error
Message = No HTTP resource was found that matches the request URI 'http://mytestserver.com/api/token?Email=bob%40example.com&password=password'.
Two things are apparent, the # has been changed to %40 which should cause a problem and the http has been changed to https.
Can restsharp be told not to convert from https and http?

Resources