Savon HTTP::ERROR but no more information? - soap

I am trying to configure my rails app to talk to a soap webservice using this code:
client = Savon::Client.new do
wsdl.document = "http://services.carsolize.com/BookingServices/dynamicdataservice.svc?wsdl"
end
response = client.request "ServiceRequest", "xmlns" => "http://tempuri.org/" do |soap, wsdl|
client.http.headers["SOAPAction"] = '"http://tempuri.org/IDynamicDataService/ServiceRequest"'
soap.body = {
"rqst" => {
"Credentials" => {
"UserName" => 'user',
"Password" => 'pass'
},
"RequestType" => "Login",
"TypeOfService" => "Unknown",
},
}
end
But all I get is a Savon::HTTP::Error in HomeController#index (and no more info) for the line starting with response.

I was facing the same error although it's not timely answer BUT posting it may in future this could be helpful for someone.
Implement OAuth2.0 with Savon
we need to put content type in request headers "Content-Type" => "text/xml"
along with Bearer token
client = Savon.client(
wsdl: [URL],
logger: Rails.logger,
log_level: :debug,
log: true,
ssl_ca_cert_file: file_path,
ssl_verify_mode: :none,
headers: { "Authorization" => "Bearer #{auth_token}", "Content-Type" => "text/xml" },
follow_redirects: true
)

I've tried to do it this way
client = Savon.client 'http://services.carsolize.com/BookingServices/dynamicdataservice.svc?wsdl'
username = '*********'
password = '*********'
response = client.request :wsdl, :login do
http.headers["SOAPAction"] = '"http://tempuri.org/IDynamicDataService/ServiceRequest"'
soap.xml = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><ServiceRequest xmlns='http://tempuri.org/'><rqst xmlns:i='http://www.w3.org/2001/XMLSchema-instance'><Credentials xmlns=''>
<Password>#{password}</Password><UserName>#{username}</UserName></Credentials><RequestType xmlns=''>Login</RequestType><TypeOfService xmlns=''>Unknown</TypeOfService></rqst></ServiceRequest></s:Body></s:Envelope>"
end
And it works fine

Related

axios POST get 400

This is driving me crazy!
Exactly the same POST request works fine in Insomina per screenshot below:
The only header Insomina has is: Content-Type: application/json.
Now, the same request in code (I even copied the code generated from Insomnia for axios) via axios in Typescript:
const saveReqConfig: AxiosRequestConfig = {
method: 'POST',
url: 'THE SAME URL USED IN Insomina',
timeout: 3000,
data: {
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
contentType: "application/json",
tags: '',
response: 'testing...',
type: 'VA',
},
headers: {
'Content-Type': 'application/json',
}
}
const normalAxios = axios.create();
const test = await normalAxios.request(saveReqConfig);
Don't understand why I am getting AxiosError: Request failed with status code 400 from code but the same request works fine in Insomina.
I think you did not set the headers correctly or you may not have setup the .create() properly.
Something like this:
const instance = axios.create({
url: '/post',
baseURL: 'https://httpbin.org',
method: 'POST',
timeout: 1000,
headers: {
Content-Type: 'application/json' // <- set your headers
}
});
let res = await instance.request({ // <- pass the data here
data: { // This should be whatever you want to post to this url. I just copied what you had.
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
tags: '',
response: 'testing...',
type: 'VA',
}
});
Are you sure you need to use the .create() factory? The normal post like this might suite your needs better?
const data= { title: 'Axios POST Request Example' };
const headers = {
Content-Type: 'application/json'
};
axios.post('url', data, { headers }).then(response => console.log(response.data.title);
Posting here in case it helps someone.
It turned out that I couldn't post the request programmatically is because of lack of a TLS certificate. I didn't know that Insomnia has the option to disable the TLS and that's why it works in Insomnia.
To disable TLS (Do NOT do this in production!) from node with axios, create an instance of axios with a https agent setting rejectedUnauthorized to false e.g.
const instance = axios.create({
httpsAgent: new https.Agent({
rejectedUnauthorized: false
})
});
Also, set the environment variable as:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

JWT Authentication with Swagger .NET Core 6

I am trying to develop an application. For Authentication I am using JWT Token. I have successfully created token. And using Postman I can authenticated. But Swagger I did whatever I should do but, It doesn't work.
After authenticated as you can see,The lock icon in the upper right is active, but the lock icons on the right of the endpoints do not work.
You can find the code part below:
JWT Authentication Part:
//JwtAuthentication
var tokenOptions = builder.Configuration.GetSection(TokenOptions.OptionSectionName).Get<TokenOptions>();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidIssuer = tokenOptions.Issuer,
ValidateIssuer = true,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = SignService.GetSymmetricSecurityKey(tokenOptions.SecurityKey),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
Swagger Gen Section:
{
options.SwaggerDoc("V1",new OpenApiInfo{
Version = "V1",
Title = "Educal API",
Description = "Main API Documantation of Educal API"
});
options.AddSecurityDefinition("Bearer,", new OpenApiSecurityScheme
{
Description = "Please insert your JWT Token into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Header,
Scheme = "Bearer",
BearerFormat = "JWT"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]{}
}
});
});
And Finally Swagger and Swagger UI section:
app.UseSwagger();
app.UseSwaggerUI(options => {
options.SwaggerEndpoint("/swagger/V1/swagger.json","Main API Documantation of Educal API");
});
Token is created successfully. When send a request from swagger to an endpoint Authorize tag I realized that swagger don't add to parameter.
For example:
curl -X 'GET' \
'https://localhost:7086/api/Manager/e1433dd0-ad45-456f-97e1-9f074e665feb' \
-H 'accept: */*'
By the way when sending request from Postman with header contains token, I can get to result.
Updated: https://stackoverflow.com/a/62337464/13490329 This answer solved my problem.

Send basic authorization in ballerina using wso2/soap module

I am using ballerina and I want to connect with WSO2 identity server for authentication.
I am not able to add Basic Authorization using wso2/soap.
Can someone provide an example?
xml body = xml `<tes:insert_employee_operation xmlns:tes="http://teste.cv">
<tes:name>{{username}}</tes:name>
<tes:age>10</tes:age>
<tes:ssn>25</tes:ssn>
</tes:insert_employee_operation>`;
soap:SoapRequest soapRequest = {
soapAction: "urn:insert_employee_operation",
payload: body
};
io:println(soapRequest);
var details = soapClient->sendReceive("/services/EmployeeService", soapRequest);
match details {
soap:SoapResponse soapResponse => {
io:println(soapResponse);
xml respostaXml = soapResponse.payload;
json respostaJson = respostaXml.toJSON({});
response.setJsonPayload(respostaJson);
_=caller->respond(response);
}
soap:SoapError soapError => io:println(soapError);
}
code
There are more fields available in the soap:SoapRequst object. See https://central.ballerina.io/wso2/soap#SoapRequest.
If you meant ws-security then can use as follows:
soap:SoapRequest soapRequest = {
soapAction: "urn:insert_employee_operation",
payload: body,
username: "foo",
password: "bar"
};
You can also set soap envelop headers using the headers field.
You can add basic authorization under the client endpoint configuration.
endpoint soap:Client soapClient {
clientConfig: {
url: "http://localhost:9000",
auth: {
scheme: http:BASIC_AUTH,
username: "is_username",
password: "is_password"
}
}
};
This will add the Authorization header into the HTTP request. The complete code will look as follows:
import ballerina/http;
import ballerina/io;
import ballerina/log;
import wso2/soap;
endpoint soap:Client soapClient {
clientConfig: {
url: "http://localhost:9000",
auth: {
scheme: http:BASIC_AUTH,
username: "is_username",
password: "is_password"
}
}
};
public function main(string... args) {
xml body = xml `<tes:insert_employee_operation xmlns:tes="http://teste.cv">
<tes:name>{{username}}</tes:name>
<tes:age>10</tes:age>
<tes:ssn>25</tes:ssn>
</tes:insert_employee_operation>`;
soap:SoapRequest soapRequest = {
soapAction: "urn:insert_employee_operation",
payload: body
};
io:println(soapRequest);
var details = soapClient->sendReceive("/services/EmployeeService", soapRequest);
match details {
soap:SoapResponse soapResponse => {
io:println(soapResponse);
xml respostaXml = soapResponse.payload;
json respostaJson = respostaXml.toJSON({});
response.setJsonPayload(respostaJson);
_ = caller->respond(response);
}
soap:SoapError soapError => io:println(soapError);
}
}

J_Spring doubts about login problems

I have the following test of a grails integration:
def http = new HTTPBuilder(loginUrl)
http.request( POST, TEXT ) {
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
send URLENC, [j_username: username, j_password: password]
response.success = { resp, reader ->
loggedIn = ! reader.text.contains("j_username")
}
}
I'm trying to mount the test in Postman, but I'm not sure if I'm doing it correctly because of this send URLENC, [j_username: username, j_password: password]
I put the POST type route, and put something like:
{
j_username: username,
j_password: password
}
And the headers parameters:
'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
'Content-type' = 'Application/json'
But it is always returning my login form in the body, does anyone know how to mount this test?
UPDATE
Actually in other projects I follow the reference and it works well. However I have developed the grails response part, did not leave an api/login route, and I believe that the login is done by the same web route /login/auth, but I can not validate the test by postman, but on the web logo perfectly.

Google Docs API: cannot set document title

I am trying to upload a file using Node and Google Docs REST API. I can upload the file just fine if I don't include the metadata, but it will always be uploaded as 'Untitled'.
But when I include the meta data I get the following error after sending my atom data and attempting to continue with the file upload:
ParseException - Content is not allowed in prolog
This is my first request to create an upload session and get a resumable-media-link
var meta = '<?xml version="1.0" encoding="UTF-8"?>'
meta+= '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:docs="http://schemas.google.com/docs/2007">'
meta+= '<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/docs/2007#document"/>'
meta+= '<title>Test</title></entry>'
var options = {
host: 'docs.google.com',
path: '/feeds/upload/create-session/default/private/full',
method: 'POST',
headers: {
'Host' : 'docs.google.com',
'Content-Length' : meta.length,
'Content-Type': 'application/atom+xml',
'GData-Version' : 3,
'Authorization' : 'GoogleLogin auth=' + authToken,
'X-Upload-Content-Type' : 'application/msword',
'X-Upload-Content-Length' : 31232
}
}
var req = https.request(options, function (res) {
// make 2nd request
});
req.end(meta);
This is what my 2nd request looks like after getting the resumable-media-link
var options = {
host: 'docs.google.com',
path: resumableMediaLink,
method: 'PUT',
headers: {
'Content-Length': data.length,
'Content-Type': 'application/msword',
'Content-Range': 'bytes 0-' + (data.length-1) +'/'+ data.length
}
}
var req = https.request(options, function (res) {
res.on('data', function (chunk) {
// ...
});
});
req.write(data);
req.end();
It seems like I am sending the atom data incorrectly. Any ideas of what I could be doing wrong?
I figured out what I was doing wrong.
I needed to set the 'Slug' header in the first POST request to initiate a resumable session.
I had it in the following request.