JAX-WS adds namespace in Signature of token - namespaces

I am accessing a third party web service using JAX-WS generated client (Java) code.
A call to a service that initiates a client session returns a Token in the response which, a.o., contains a Signature. The Token is required in subsequent calls to other services for authentication purposes.
I learned from using SoapUI that the WS/Endpoint requires the Token to be used as-is... meaning everything works fine when I literally copy the Token (which is one big line) from the initial response to whatever request I like to make next.
Now I am doing the same in my JAX-WS client. I retrieved a Token (I copied it from the response which I captured with Fiddler) and I tested it succesfully in a subsequent call using SoapUI.
However, when performing a subsequent call to a service using the JAX-WS client, the Signature part in the Token is changed. It should look like:
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">...</Signature>
But (when capturing the request with Fiddler) it now looks like:
<Signature:Signature xmlns:Signature="http://www.w3.org/2000/09/xmldsig#" xmlns="http://www.w3.org/2000/09/xmldsig#">...</Signature:Signature>
Apparently this is not acceptable according to the WS/Endpoint so now I'd like to know:
Why is the Token marshalled back this way?
More importantly, how can I prevent my client from doing that?
Thanks in advance!

Have you tested it? It should work nevertheless. The original signature used the defautl namespace (...xmldigsig) the JAXB version uses the same namespace but explicit says that the Signature element belongs to that namespae (Signature:Signature). The effect is the same, both xml express that Signature is in the http://www.w3.org/2000/09/xmldsig# namespace
You can customize the jaxby output with #XMLSchema on the package info, #XMLType on the class or inside the element.
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html

By the help of #Zielu I was able to solve this by altering package-info.java (in the package of the generated files) like so:
#javax.xml.bind.annotation.XmlSchema(
namespace = "http://namespaceofthirdparty-asingeneratedversionof package-info.java"
, xmlns = {
#javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.w3.org/2000/09/xmldsig#", prefix = "")
}
, elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package com.where.generated.files.are;

Related

Exception: '<' is an invalid start of a value

I have a Blazor Webassembly project with a controller method as follows:
[HttpGet]
public async Task<List<string>> GetStatesForProfile()
{
IConfigurationSection statesSection = configuration.GetSection("SiteSettings:States");
var sections = statesSection.GetChildren();
var states = statesSection.GetChildren().Select(s => s.Key).ToList<string>();
return states;
}
The razor page calls this method:
private async Task<bool> GetStatesModel()
{
try
{
States = await http.GetJsonAsync<List<string>>("api/account/getstatesforprofile");
...
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}, Inner: {ex.InnerException.Message}");
}
I get this Exception:
Exception: '<' is an invalid start of a value.
I read these values from appsettings.json file, And there is no '<' in values.
{
"SiteSettings": {
"States": {
"New York": ["NYC"],
"California": ["Los Angeles", "San Francisco"]
}
}
Also I put a breakpoint in the controller method and it doesn't hit.
What is this error? Is it from parsing json? and how to resolve this?
I had a very similar problem.
In the end it turned out that my browser had cached the HTML error page (I guess I had some problems with the code when I first tried it). And no matter how I tried fixing the code I still only got the error from cache. Clearing my cache also cleared the problem.
It happens when you're trying to access an API that doesn't exist. You have to check your API project connectionstring under AppSettings and make sure it's correct and running. If it's a Blazor project, you can set it as your default project, execute and see if you get a json response.
Most probably the response you are receiving is html instead of actual JSON format for the endpoint you are requesting. Please check that.
An as HTML usually starts with <html> tag, the JSON validator fails on the very first character.
You should also clear any cache, that might be interfering with the returned data. (this has helped people resolve this same issue)
I know this is an old question, but it's one of the top results when Googling the error.
I've just spent more time than I care to admit to tracking down this error. I had a straightforward Blazor hosted app, basically unchanged from the template. It worked just fine when run locally, but when published to my web host API calls failed. I finally figured out that the problem was that I was running the publish from the Client project. When I changed to the Server project it worked properly.
Hopefully my long frustration and slight stupidity will save someone else making a similar mistake.
Seems like your api is not not accessible and its returning error HTML page by default.
You can try below solution:-
I think you are using httpclient to get data to blazor application.
If you have separate projects in solution for blazor and web api,
currently your startup application may set to run blazor project only.
Change startup projects to multiple (blazor and web api app) and give httpClient url in startup of blazor application, as webApi application url, that may solve your issue.
This error indicates a mismatch of the project targeting framework version and installed runtime on the machine. So make sure that the target framework for your project matches an installed runtime - this could be verified by multiple means; one of them is to check out the Individual Components tab of the Visual Studio Installer and lookup the target version.
E.g., there is the TargetFramework attribute in the proj file:
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
Then launch the Visual Studio Installer, click Modify, and visit the Individual Components tab:
Install the missing runtime (.NET 5 Runtime in this case) and you're good to go.
I got the same error. Red herring. use your browser or postman to check your api endpoint is returning the json data and not some HTML. In my case my "api/companytypes" had a typo.
private CompanyType[] companytypesarray;
private List<CompanyType> CompanyTypeList;
private List<CompanyType> CompanyTypeList2;
public async Task<bool> LoadCompanyTypes()
{
//this works
CompanyTypeList = await Http.GetFromJsonAsync<List<CompanyType>>("api/companytype");
//this also works reading the json into an array first
companytypesarray = await Http.GetFromJsonAsync<CompanyType[]>("api/companytype");
CompanyTypeList2 = companytypesarray.ToList();
return true;
}
I know this is an old question, but I had the same problem. It took some searching, but I realized that the return data was in XML instead of JSON.
I'm assuming your "http" variable is of type HttpClient, so here's what I found worked for me.
By setting the "Accept" header to allow only JSON, you avoid a miscommunication between your app and the remote server.
http.DefaultRequestHeaders.Add("Accept", "application/json");
States = await http.GetJsonAsync<List<string>>("api/account/getstatesforprofile");
I had the same issue when passing in an empty string to a controller method. Creating a second controller method that doesn't accept any input variables, and just passing an empty string to the first method helped to fix my problem.
[HttpGet]
[ActionName("GetStuff")]
public async Task<IEnumerable<MyModel>> GetStuff()
{
return await GetStuff("");
}
[HttpGet("{search}")]
[ActionName("GetStuff")]
public async Task<IEnumerable<MyModel>> GetStuff(string search)
{
...
}
Versions of package
Try to update your packages to old or new version. In my case, system.net.http.json is updated from 6.0 to 5.0
Likely you are using an Asp.NetCore hosted WASM application. By default the client's App.razor has something similar to:
<CascadingAuthenticationState>
<Router AppAssembly="#typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView DefaultLayout="#typeof(MainLayout)"
RouteData="#routeData">
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
<Authorizing>
<Loading Caption="Authorizing..."></Loading>
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="#typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Herein lies the problem. Since the Client and Server share the same base address, when the application cannot find "api/account/getstatesforprofile" it gives you the client's "Sorry, there's nothing at the address" page. Which is of course HTML.
I have not found the solution to this issue, but I am working on it and will reply once I find an issue.
I was having the same problem,
"JsonReaderException: '<' is an invalid start of a value."
In my case the url for the REST service was wrong.
I was using the URL from the client project. Then I looked at the Swagger screen,
https://localhost:44322/swagger/index.html
and noticed the right URL should start with "44322"...
Corrected, worked.
In my case, I had a comma (,) written mistakenly at the beginning of the appsettings.json file ...
Just check your file and verify
///////
my error details
//////
System.FormatException HResult=0x80131537 Message=Could not parse the JSON file.
Source=Microsoft.Extensions.Configuration.Json StackTrace: at line 16 This exception was originally thrown at this call stack: [External Code] Inner Exception 1: JsonReaderException: ',' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
////
For me, most of the time it is the #lauri-peltonen answer above. However, now and again, depending on who wrote the controller I have found that this will work in Swagger but not when you call it via the client (at least in this Blazor project we are on.)
[HttpGet]
[Route("prog-map-formulations")]
public async Task<List<GetProgramMapFormulationsResult>> GetProgramMapFormulations(int formulationId)
{
...
}
It sends the request as:
api/formulation-performance-program-map/analytical-assoc-values?formulationId=1
And I get results in Swagger but failes with the '<' OP error.
When I change ONLY the route to:
[HttpGet]
[Route("prog-map-formulations/{formulationId:int}")]
public async Task<List<GetProgramMapFormulationsResult>> GetProgramMapFormulations(int formulationId)
{
...
}
It sends the request as:
api/formulation-performance-program-map/analytical-assoc-values/1
And this works in both Swagger as well as from the Client side in Blazor.
Of course, once updated, I did have to clear the cache!
If you delete "obj" folder in your directory then clean the solution and rebbuild it the exception will be resolved
In all these, there is two things that was my issue and realized, first off was that Route[("api/controller")] instead of Route[("api/[controller]")], that is missing square brackets. In the second exercise I was doing, with the first experience in mind, was from the name of the database. The database had a dot in the name (Stock.Inventory). When I change the database name to StockInventory it worked. The second one I am not so sure but it worked for me.

How to set proxy server for Json Web Keys

I'm trying to build JWKS object for google JSON web keys to verify the signature of JWT token received from google. Inside our corporate environment, we need to set the proxy server to reach out external one. Below code runs outside the corporate environment.
HttpsJwks https_jwks = new HttpsJwks(GOOGLE_SIGN_KEYS);
List<JsonWebKey> jwks_list = https_jwks.getJsonWebKeys();
Library: jose4j0.4.1
Thanks in advance.
HttpsJwks uses the SimpleGet interface to make the HTTP call. By default it's an instance of Get, which uses java's HttpsURLConnection. So I think using the https proxy properties should work - see https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html for more about https.proxyHost and https.proxyPort.
If you need to do something more exotic for whatever reason, you can set your own implementation/instance of SimpleGet on the HttpsJwks instance too.

invalid xml request for calculator service

I'm completely new to axis2c and I've just downloaded and unpacked
axis2c 1.6 for Windows (binary release).
I've followed the installation instructions and have successfully
started axis2_http_server.
Trying to access the Calculator service's WSDL works fine but any call to
the service's add method returns "invalid XML in request" as well as the
same text is shown in the console window where axis2_http_server is
running.
I've also tried soapUI. The request shown is:
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:typ="http://ws.apache.org/axis2/services/Calculator/types">
<soapenv:Header/>
<soapenv:Body>
<typ:add>
<param_1>1.0</param_1>
<param_2>1.0</param_2>
</typ:add>
The response is
<soapenv:Fault>
<faultcode>soapenv:Sender</faultcode>
<faultstring>Invalid XML format in request</faultstring>
</soapenv:Fault>
The problem is issued in in calc.c (function axis2_calc_add()), where
seq_node = axiom_node_get_first_child(complex_node, env);
returns NULL.
Calculator service example has multiple issues that prevents it to work.
Firstly, implementation of add operation is invalid, it expects request like that (here is only contents of soap body):
<typ:add>
<complex_node>
<seq_node>
<param_1>1</param_1>
<param_2>2</param_2>
</seq_node>
</complex_node>
</typ:add>
Looks like someone committed that code by mistake.
Secondly, code that is implemented in Calculator service does not allow to have whitespaces between request elements. It takes any first node hoping it is an element, but fails, because takes text node between elements.
To start that example without modification of the service:
use one of sub, div, mul operations.
remove all whitespaces in request element like that:
<typ:sub><param_1>3</param_1><param_2>2</param_2></typ:sub>
Then you will be able to call the service.
If you want to see fully working Calculator service, you can compile Axis2/C from axis2-unofficial project (or install it from binary archive).
Or, you can apply that changes to the original source code and recompile it.

calling a webservice without using a wsdl file

I need to make a call to a webservice and at the moment i am doing it this way:
private var myWebService:WebService = new WebService();
myWebService.loadWSDL('path to wsdl file');
myWebService.addEventListener(ResultEvent.RESULT , function(event:ResultEvent):void {
trace(event);
});
myWebService.addEventListener(FaultEvent.FAULT , function(event:FaultEvent):void {
trace(event);
});
myWebService.soapcallName();
Now i would like to do the same thing but without loading the WSDL file and doing the soapcalls directly to the right url. Is this possible?
Yes, I had to do this when our WS calls had to hit a proxy in a DMZ, but the WSDL for the ACTUAL service was behind a firewall and unreachable. But it is a tricky process.
First you will need to create the soap post requests manually. You can read all about the structure on wikipedia http://en.wikipedia.org/wiki/SOAP . This means you will need to generate all calls manually since you can't say SomeService.SomeMethod without the wsdl loaded. Now the next problem you will face is actually sending it out. Because you need to add custom http headers on a POST, you will need to build the full request document (strings and line breaks etc) and send it over a socket (HTTPService will not support custom headers on a POST). If you need more help getting this going, I can add further examples on here.
Example:
You need to basically create a method to generate SOAP Envelopes. Here's a quick i.e. from the link I gave you...
private function getStockPrice(symbol:String):String{
// you can do this with xml also and call toString() on it later
var envelope:String = "<?xml version=\"1.0\"?>";
envelope += "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">";
envelope += "<soap:Header></soap:Header>";
envelope += "<soap:Body><m:GetStockPrice xmlns:m=\"http://www.example.org/stock\">";
envelope += "<m:StockName>" + symbol + "</m:StockName>";
envelope += "</m:GetStockPrice></soap:Body></soap:Envelope>";
return envelope;
}
Then you call getStockPrice("IBM") which will return the ready to go SOAP envelope that you will use as the POST body of your call. Note that in the example, you will have to know the information that would have been in the WSDL ahead of time like method names, param names etc. Use the Socket() class to send the post body to the server since you will need to add a custom SOAPAction header. If you need help with that part, here is a class to begin hacking on that already does that... use it instead of HTTPService. RestHTTPService.

How to get HTTP status code in HTTPService fault handler

I am calling a server method through HTTPService from client side. The server is a RestFul web service and it might respond with one of many HTTP error codes (say, 400 for one error, 404 for another and 409 for yet another). I have been trying to find out the way to determine what was the exact error code sent by the server. I have walked teh entire object tree for the FaultEvent populated in my fault handler, but no where does it tell me the error code. Is this missing functionality in Flex?
My code looks like this:
The HTTP Service declaration:
<mx:HTTPService id="myServerCall" url="myService" method="GET"
resultFormat="e4x" result="myServerCallCallBack(event)" fault="faultHandler(event)">
<mx:request>
<action>myServerCall</action>
<docId>{m_sDocId}</docId>
</mx:request>
</mx:HTTPService>
My fault handler code is like so:
private function faultHandler(event : FaultEvent):void
{
Alert.show(event.statusCode.toString() + " / " + event.fault.message.toString());
}
I might be missing something here, but:
event.statusCode
gives me the status code of the HTTP response.
So I can successfully do something like this in my fault handler function:
public function handleFault(faultEvent:FaultEvent):void
{
if (faultEvent.statusCode == 401)
{
Alert.show("Your session is no longer valid.", "", Alert.OK, this, loginFunc);
}
else
{
Alert.show("Failed with error code: " + faultEvent.statusCode as String);
}
}
Looks like you are out of luck: http://fantastic.wordpress.com/2007/12/26/flex-is-not-friendly-to-rest/
You may have to use ExternalInterface to get this handled in JS and then communicated to Flex.
The Flash Player needs help from the browser to be able to access the HTTP status code; therefore, this is not available on all platforms. For me, it failed with Flash Player 10.3.183.11 and Firefox 3.6.26, but worked with IE 8 on Windows 7.
The Adobe help for the FaultEvent.statusCode property hints at this, but unfortunately doesn't go into details:
this property provides access to the HTTP response status code (if available), otherwise the value is 0
So, if you absolutely need the status code, bad luck; if it's just to generate a better or friendlier error message for some frequent error conditions, it may be sufficient.
as3httpclient as posted by Ross is friendly to Rest, and provides you with the HTTP status code, as long as you're developing for AIR and not a browser-based app.
I could not get as3httpclient to work from the browser, even when making requests to the same origin. There's documentation stating you need to set up a socket policy file server to get this to work. Not scalable for our uses so I setup a Proxy web service on the same host running the flex app.
I use HTTPService to make the call to the proxy web service, which forwards the request to the destination, and the proxy web service returns the http status code and message body back to the HTTPService in xml.
Try using this instead of HTTPService:
http://code.google.com/p/as3httpclient/