wso2 issues using call mediator on magento2 api - wso2

I'm trying to create a service chain using a wso2 sequence with a payload factory and call mediator.
I'm using wso2 3.2.0 and Magento 2.4.1.
My goal is to ask Magento a token using admin credentials, and returning the token to the client. The payload to make the request should be defined inside the sequence, and there should also be other call mediators after the first one.
I've defined my API with the following definition, and I'm using dynamic endpoints
openapi: 3.0.1
info:
title: Magento
version: v1
servers:
- url: /
security:
- default: []
paths:
/call:
get:
parameters: []
responses:
'200':
description: ok
security:
- default: []
x-auth-type: None
x-throttling-tier: Unlimited
x-wso2-application-security:
security-types:
- oauth2
optional: false
post:
parameters: []
responses:
'200':
description: ok
security:
- default: []
x-auth-type: None
x-throttling-tier: Unlimited
x-wso2-application-security:
security-types:
- oauth2
optional: false
components:
securitySchemes:
default:
type: oauth2
flows:
implicit:
authorizationUrl: 'https://test.com'
scopes: {}
x-wso2-cors:
corsConfigurationEnabled: false
accessControlAllowOrigins:
- '*'
accessControlAllowCredentials: false
accessControlAllowHeaders:
- authorization
- Access-Control-Allow-Origin
- Content-Type
- SOAPAction
- apikey
- testKey
accessControlAllowMethods:
- GET
- PUT
- POST
- DELETE
- PATCH
- OPTIONS
x-wso2-production-endpoints:
type: default
x-wso2-sandbox-endpoints:
type: default
x-wso2-basePath: /magento/v1
x-wso2-transports:
- http
- https
x-wso2-response-cache:
enabled: false
cacheTimeoutInSeconds: 300
The sequence for my API looks like so,
<?xml version="1.0" encoding="UTF-8"?>
<sequence name="service_chain_request_magento" trace="disable" xmlns="http://ws.apache.org/ns/synapse">
<property action="remove" name="REST_URL_POSTFIX" scope="axis2"/>
<property name="FORCE_HTTP_1.0" scope="axis2" type="STRING" value="true"/>
<property name="DISABLE_CHUNKING" scope="axis2" type="STRING" value="true"/>
<payloadFactory media-type="json">
<format>{"username":"<username>","password":"<pwd>"}</format>
<args/>
</payloadFactory>
<property name="messageType" value="application/json" scope="axis2"/>
<call blocking="true">
<endpoint>
<http method="post" uri-template="http://<magento_ip>/index.php/rest/all/V1/integration/admin/token">
<timeout>
<duration>6000</duration>
<responseAction>fault</responseAction>
</timeout>
</http>
</endpoint>
</call>
<enrich>
<source type="body" clone="true"/>
<target type="property" action="child" property="body_of_first_call"/>
</enrich>
<log level="full"/>
</sequence>
Where everything inside <> is, of course, replaced with proper values.
When I try to call my API POST - https://<ip>:8243/magento/v1/call using this sequence, I get the following result:
{
"message": "One or more input exceptions have occurred.",
"errors": [
{
"message": "\"%fieldName\" is required. Enter and try again.",
"parameters": {
"fieldName": "username"
}
},
{
"message": "\"%fieldName\" is required. Enter and try again.",
"parameters": {
"fieldName": "password"
}
}
],
}
even though, inspecting the logs, this is the response:
INFO - LogMediator {api:admin--Magento:vv1} To: http://<magento_ip>/index.php/rest/all/V1/integration/admin/token, MessageID: c6b5eb10-89a1-42df-9f0d-098d605dae91, correlation_id: c6b5eb10-89a1-42df-9f0d-098d605dae91, Direction: request, Payload: "brni5ub8o4vfltfups9swrwk3biw3cd4"
As what I can understand, the Payload field is correctly returning the expected response from Magento rest APIs, but it looks like the REST client I'm using (both Postman and the wso2 console) are returning the error response from the API, like the request is made a second time without the post body.
If I replace the call mediator with the To header like this:
<header name="To" scope="default" value="http://<magento_ip>/index.php/rest/all/V1/integration/admin/token"/>
the call just works and returns the expected payload, but then I cannot chain other call mediators.
Here's the specs about the Magento API I'm calling https://magento.redoc.ly/2.4.2-admin/tag/integrationadmintoken
How can I resolve this?
Thanks in advance

Related

Javascript application is unable to generate access token from WSO2 gateway URL

We have on premise WSO2 stack for managing the api subscription where there are client applications created in the wso2 store URL for generating access tokens. One of the development team in our organization is trying to generate the access token from the client id and secret by the means of javascript. The tokens are not getting generated and resulting into CORS issue. I have checked the documentations for similar issues and I have made change in the TokenAPI.xml file located under the <API_M>/repository/deployment/server/synapse-configs/default/api directory by adding the outsequence property. Unfortunately this did not solve the issue. I have read a few documentations and verified the cors configuration in the api manager.xml file it looked fine to me.
const token =
"Base64(consumer-key:consumer-secret)";
const url = "https://<gateway_Url>/token";
const res = axios({
method: "post",
url: url,
data: "grant_type=client_credentials",
headers: {
"Authorization": `Basic ${token}`,
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
},
});
cat /data/wso2/wso2am-2.6.0/repository/deployment/server/synapse-configs/default/api/_TokenAPI_.xml
<api xmlns="http://ws.apache.org/ns/synapse" name="_WSO2AMTokenAPI_" context="/token">
<resource methods="POST" url-mapping="/*" faultSequence="_token_fault_">
<inSequence>
<property name="uri.var.portnum" expression="get-property('keyManager.port')"/>
<property name="uri.var.hostname" expression="get-property('keyManager.hostname')"/>
<send>
<endpoint>
<http uri-template="https://{uri.var.hostname}:{uri.var.portnum}/oauth2/token">
<timeout>
<duration>60000</duration>
<responseAction>fault</responseAction>
</timeout>
</http>
</endpoint>
</send>
</inSequence>
<outSequence>
<property name="Access-Control-Allow-Headers" scope="transport" value="authorization,Access-Control-Allow-Origin,Content-Type,Action"></property>
<send/>
</outSequence>
</resource>
<handlers>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerCacheExtensionHandler"/>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.common.SynapsePropertiesHandler"/>
</handlers>
</api>
Error - Access to XMLHttpRequest at 'https://api-uat.ucl.ac.uk/token' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
You might have to add the CORS handler to the token API under handlers.
<handler class= "org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler">
<property name="apiImplementationType" value="ENDPOINT"/>
</handler>

WSO2 ESB - Could not capture the header in the POST message to REST API

I sent this message:
curl -X POST http://192.168.0.179:8280/esb/api/CreateAddressID -H "content-
type: application/json" --data #evCaptureJSONPropertiesInvalid.json
I was trying to capture the header "content-type: application/json" .
This was my configuration in my API Resource:
<!-- Capture the payload values START-->
<property name="contentType" expression="$trp:Content-Type" scope="default" type="STRING" value="value"/>
and then I tried to retrieve it in the log mediator as shown below:
<log description="Request Log" level="custom">
<property name="Content-Type" expression="$ctx:contentType"/>
</log>
Yet when I saw the output in the console it did not appear what I saw instead was:
[2018-12-05 15:15:07,933] [EI-Core] INFO - LogMediator content-Type = value
Could someone kindly assist? Also thank you in advance.
Both
<property expression="get-property('transport', 'Content-Type')" name="contenttype"/>
<property expression="$trp:Content-Type" name="contenttype"/>
Should work. I suspect the header is case sensitive and it will work when you use `-H "Content-Type: application/json"

wso2 server redeployment error "Faulty Carbon Applications."

I am getting an error whenever I tried to redeploy the app to the esb. I am trying to merge the 2 response from different api and then map and manipulate that response. I am also using the latest 5.0.0 BETA version both esb tooling and esb.
Here is the fault reason
org.apache.axis2.deployment.DeploymentException: API deployment from
the file :
/Users/me/Downloads/wso2esb-5.0.0-BETA2/tmp/carbonapps/-1234/1468999438631movieapiApp_1.0.0.car/movieAPI_1.0.0/movieAPI-1.0.0.xml
: Failed. at
org.apache.synapse.deployers.AbstractSynapseArtifactDeployer.deploy(AbstractSynapseArtifactDeployer.java:213)
at
org.wso2.carbon.application.deployer.synapse.SynapseAppDeployer.deployArtifacts(SynapseAppDeployer.java:131)
at
org.wso2.carbon.application.deployer.internal.ApplicationManager.deployCarbonApp(ApplicationManager.java:263)
at
org.wso2.carbon.application.deployer.CappAxis2Deployer.deploy(CappAxis2Deployer.java:72)
at
org.apache.axis2.deployment.repository.util.DeploymentFileData.deploy(DeploymentFileData.java:136)
at
org.apache.axis2.deployment.DeploymentEngine.doDeploy(DeploymentEngine.java:807)
at
org.apache.axis2.deployment.repository.util.WSInfoList.update(WSInfoList.java:144)
at
org.apache.axis2.deployment.RepositoryListener.update(RepositoryListener.java:377)
at
org.apache.axis2.deployment.RepositoryListener.checkServices(RepositoryListener.java:254)
at
org.apache.axis2.deployment.RepositoryListener.startListener(RepositoryListener.java:371)
at
org.apache.axis2.deployment.scheduler.SchedulerTask.checkRepository(SchedulerTask.java:59)
at
org.apache.axis2.deployment.scheduler.SchedulerTask.run(SchedulerTask.java:67)
at
org.wso2.carbon.core.deployment.CarbonDeploymentSchedulerTask.runAxisDeployment(CarbonDeploymentSchedulerTask.java:93)
at
org.wso2.carbon.core.deployment.CarbonDeploymentSchedulerTask.run(CarbonDeploymentSchedulerTask.java:138)
at
java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) at
java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at
java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745) Caused by:
org.apache.axis2.deployment.DeploymentException: API deployment from
the file :
/Users/me/Downloads/wso2esb-5.0.0-BETA2/tmp/carbonapps/-1234/1468999438631movieapiApp_1.0.0.car/movieAPI_1.0.0/movieAPI-1.0.0.xml
: Failed. at
org.apache.synapse.deployers.AbstractSynapseArtifactDeployer.deploy(AbstractSynapseArtifactDeployer.java:201)
... 20 more Caused by:
org.apache.synapse.deployers.SynapseArtifactDeploymentException: API
deployment from the file :
/Users/me/Downloads/wso2esb-5.0.0-BETA2/tmp/carbonapps/-1234/1468999438631movieapiApp_1.0.0.car/movieAPI_1.0.0/movieAPI-1.0.0.xml
: Failed. at
org.apache.synapse.deployers.AbstractSynapseArtifactDeployer.handleSynapseArtifactDeploymentError(AbstractSynapseArtifactDeployer.java:474)
at
org.apache.synapse.deployers.APIDeployer.deploySynapseArtifact(APIDeployer.java:71)
at
org.wso2.carbon.rest.api.ApiDeployer.deploySynapseArtifact(ApiDeployer.java:34)
at
org.apache.synapse.deployers.AbstractSynapseArtifactDeployer.deploy(AbstractSynapseArtifactDeployer.java:194)
... 20 more Caused by: org.apache.synapse.SynapseException: Duplicate
resource definition by the name: movieapi at
org.apache.synapse.config.SynapseConfiguration.handleException(SynapseConfiguration.java:1627)
at
org.apache.synapse.config.SynapseConfiguration.addAPI(SynapseConfiguration.java:414)
at
org.apache.synapse.deployers.APIDeployer.deploySynapseArtifact(APIDeployer.java:59)
... 22 more
and here's my api
<?xml version="1.0" encoding="UTF-8"?>
<api context="/movieapi" name="movieapi" xmlns="http://ws.apache.org/ns/synapse">
<resource methods="GET" uri-template="/*">
<inSequence>
<property name="ROOT" scope="default">
<root:movie xmlns:root="www.wso2esb.com"/>
</property>
<log level="full"/>
<clone continueParent="true" id="movie" sequential="true">
<target>
<sequence>
<send>
<endpoint>
<address format="rest" uri="https://api.themoviedb.org/3/movie/tt0918940?api_key=code&append_to_response=casts,images%22"/>
</endpoint>
</send>
</sequence>
</target>
<target>
<sequence>
<send>
<endpoint>
<address format="rest" uri="https://www.omdbapi.com/?type=movie&i=tt0918940"/>
</endpoint>
</send>
</sequence>
</target>
</clone>
</inSequence>
<outSequence>
<aggregate id="movie">
<completeCondition>
<messageCount max="-1" min="-1"/>
</completeCondition>
<onComplete enclosingElementProperty="ROOT" expression="//jsonObject" xmlns:dummy="http://org.dummy" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<datamapper config="gov:datamapper/movieapiMapping.dmc" inputSchema="gov:datamapper/movieapiMapping_inputSchema.json" inputType="JSON" outputSchema="gov:datamapper/movieapiMapping_outputSchema.json" outputType="JSON"/>
<property name="messageType" scope="axis2" type="STRING" value="application/json"/>
<respond/>
</onComplete>
</aggregate>
</outSequence>
<faultSequence/>
</resource>
</api>
and this is from the terminal
[2016-07-20 15:36:48,890] ERROR - DataMapperMediator DataMapper mediator : mapping configuration is null
The error you are getting in the terminal DataMapperMediator DataMapper mediator : mapping configuration is null is because the relevant registry resources are not deployed (more precisely, the configuration .dmc file). When you are deploying the capp, make sure that all the registry resources are included as well. Also when the capp deployment fails, can you check in the management console for any faulty services/APIs?
You get the error indicating Data mapper configurations null. So you have to add relevant configurations as you given in the proxy:
<datamapper config="gov:datamapper/movieapiMapping.dmc" inputSchema="gov:datamapper/movieapiMapping_inputSchema.json" inputType="JSON" outputSchema="gov:datamapper/movieapiMapping_outputSchema.json" outputType="JSON"/>
For example: You indicated about gov:datamapper/movieapiMapping.dmc
This should be available in governance registry.Please deploy relevant configs in to ESB.
Open the pom.xml file inside your CompositeApplication.
Edit it in the Design mode.
Under dependencies, you can see the artifacts which you can include.
Tick the checkbox near your relevant Registry artifact. Save pom file.
Now redeploy the application to the server or Regenerate your car file

I/O exception while sending request to axis2 server in WSO2 ESB

When I send a request to axis2 client I get a error
Proxy:
<proxy name="SOAP_Body" startOnLoad="true">
<target>
<inSequence>
<switch xmlns:m0="http://services.samples"
source="//m0:getQuote/m0:request/m0:symbol">
<case regex="foo">
<log level="custom">
<property name="a" value="s"/>
</log>
<send>
<endpoint>
<address uri="http://localhost:9001/services/SimpleStockQuoteService?wsdl"/>
</endpoint>
</send>
</case>
<case regex="bar">
<log level="custom">
<property name="b" value="a"/>
</log>
<send>
<endpoint>
<address uri="http://localhost:9002/services/SimpleStockQuoteService?wsdl"/>
</endpoint>
</send>
</case>
<default>
<property name="symbol"
expression="fn:concat('Normal Stock - ', //m0:getQuote/m0:request/m0:symbol)"/>
</default>
</switch>
</inSequence>
<outSequence>
<send/>
</outSequence>
</target>
ELB in 9443 offset 0, ESB in 9444 offset 1
so I have sent a request to http://localhost:8280/services/SOAP_Body of ELB
and I get the following error when I have sent a request thru axis2client in esb
[java] 15/06/30 15:40:43 INFO httpclient.HttpMethodDirector: I/O exception
(java.net.ConnectException) caught when processing request: Connection refused:
connect
When I send through SOAP UI for the above endpoint I get
Wed Jul 01 10:48:06 IST 2015:ERROR:Exception in request: org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8280 refused
Wed Jul 01 10:48:06 IST 2015:ERROR:An error occured [Connection to http://localhost:8280 refused], see error log for details
Wed Jul 01 10:48:06 IST 2015:INFO:Error getting response for [SimpleStockQuoteServiceSoap11Binding.getQuote:Request 1]; org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8280 refused
I have enabled clustering and other configuration as in 1
But when I send request to ESB alone without getting through ELB I get the desired output.
When I give AllowAll in axis2.xml in ELB i get the new error in ELB server
Error - DynamicLoadbalanceEndpoint application member not available
What would be the problem? Please help me out.
Did any of you got sample 57 in wso2 esb for dynamic endpoint working? If yes please help me in configuring. I have configured as in documentation but i couldnt get it working.
Thanks.
There is not enough information in your question.
Post the full stack trace.
Where is your axis 2 service being hosted? WSO2AS?
What is your axis 2 service endpoint.
Post your send mediator xml config.
Have you checked whether the endpoint is working correctly...
Please try this on the web browser:
http://localhost:8280/services/SOAP_Body?wsdl
and see whether or not you get the wsdl of the proxy.

WSO2 ESB proxy service Escaping JSON payload when passing to jaggery js

I am POSTing to a ESB (4.6.0) proxy service with a JSON payload. This is a pass through proxy service that routes to a jaggery JS app. The jaggery app is trying to access the JSON from the payload, but it is unable to because the JSON strings are escaped.
Here are the request headers (from web --> ESB):
POST /services/testJaggPS HTTP/1.1
Host: pb-dvwa8:7280
Content-Length: 29
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
{
"PARAM": "hello world"
}
And here is the JSON response from the jaggery app:
{"RESPONSE" : {"test" : "hi", "PARAM" : null, "content" : "{\n \"PARAM\" : \"HELLO WORLD\" \n}"}}
Note that "content" (variable that stores JSON payload from web) is being escaped.
I have looked into message builders/formatters, but it has not solved this issue. Here is my current proxy service (probably don't need all of the message builders):
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="testJaggPS"
transports="https http"
startOnLoad="true"
trace="disable">
<target endpoint="jaggRouter">
<inSequence>
<builder>
<messageBuilder contentType="application/xml"
class="org.apache.axis2.builder.ApplicationXMLBuilder"
formatterClass="org.apache.axis2.transport.http.ApplicationXMLFormatter"/>
<messageBuilder contentType="application/xop+xml"
class="org.apache.axis2.builder.MTOMBuilder"/>
<messageBuilder contentType="multipart/related"
class="org.apache.axis2.builder.MIMEBuilder"/>
<messageBuilder contentType="application/json"
class="org.apache.axis2.json.JSONBuilder"
formatterClass="org.apache.axis2.json.JSONMessageFormatter"/>
<messageBuilder contentType="application/x-www-form-urlencoded"
class="org.apache.axis2.builder.XFormURLEncodedBuilder"
formatterClass="org.apache.axis2.transport.http.XFormURLEncodedFormatter"/>
<messageBuilder contentType="text/xml"
class="org.apache.axis2.builder.SOAPBuilder"
formatterClass="org.apache.axis2.transport.http.SOAPMessageFormatter"/>
<messageBuilder contentType="application/soap+xml"
class="org.apache.axis2.builder.SOAPBuilder"
formatterClass="org.apache.axis2.transport.http.SOAPMessageFormatter"/>
<messageBuilder contentType="application/json/badgerfish"
class="org.apache.axis2.json.JSONBadgerfishOMBuilder"/>
</builder>
<property name="messageType" value="application/json" scope="axis2"/>
<property name="contentType" value="application/json" scope="axis2"/>
</inSequence>
<outSequence>
<property name="messageType" value="application/json" scope="axis2"/>
<property name="contentType" value="application/json" scope="axis2"/>
<send/>
</outSequence>
</target>
</proxy>
And here is my jaggery code:
<%
// load core files
response.contentType = 'application/json';
var url = request.getRequestURL();
var theContent = request.getContent();
// note null 'PARAM' and escaped 'content'
response.content = {"RESPONSE" : {
"test" : "hi",
"PARAM" : theContent.PARAM,
"content" : theContent
}};
%>
There was an issue with Jaggery's automatic JSON parsing when you have additional stuff in the Content-Type header such as character encoding etc. It was fixed in master branch.
But, if you are trying with an earlier version, you will have to manually parse the content using JSON.parse(). i.e. replace your
var theContent = request.getContent();
line in Jaggery file, with
var theContent = JSON.parse(request.getContent());