Im new comer to Wso2 esb. Now I'm working with tcp protocol and proxy service. I have some question. I send some message to the proxy service through tcp protocol. I need get this message to the property mediator in the proxy service. But my way not catch that value in the property mediator.
Here is my proxy service
<?xml version="1.0" encoding="UTF-8"?>
<proxy name="TCPProxyService" startOnLoad="true" transports="tcp" xmlns="http://ws.apache.org/ns/synapse">
<target>
<inSequence>
<property description="" expression="get-property('message')" name="MessageValue" scope="default" type="STRING"/>
<log description="" level="custom">
<property name="property_name" value="============================="/>
<property expression="get-property('MessageValue')" name="inputValue"/>
</log>
<sequence key="in-sequence"/>
<log/>
<respond/>
</inSequence>
<outSequence/>
<faultSequence/>
</target>
<parameter name="transport.tcp.responseClient">true</parameter>
<parameter name="transport.tcp.inputType">string</parameter>
<parameter name="transport.tcp.recordDelimiter">|</parameter>
<parameter name="transport.tcp.contentType">text/plain</parameter>
<parameter name="transport.tcp.port">6789</parameter>
<parameter name="transport.tcp.recordDelimiterType">character</parameter>
</proxy>
Here is my Java client for send tcp request
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String delimiter = "|";
int modifiedSentence;
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String message = "Pietoo,Klaas,also" + delimiter;
outToServer.writeBytes(message);
outToServer.flush();
while ((modifiedSentence = inFromServer.read()) > -1){
System.out.print((char)modifiedSentence);
}
clientSocket.close();
}
}
I tried to add below property mediator with get-property expression. What is the wrong with this.
property description="" expression="get-property('message')" name="MessageValue" scope="default" type="STRING"/>
try a <log level="full"/> in your proxy def, send it a message with your java client and have a look to wso2-esb-service.log : you should see a soap message like this
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<text xmlns="http://ws.apache.org/commons/ns/payload">your|data</text>
</soapenv:Body>
</soapenv:Envelope>
You can get the text value with :
<property xmlns:tp="http://ws.apache.org/commons/ns/payload" name="MessageValue" expression="$body/tp:text"/>
Related
I Have This API And I Used the Message Mediation Below to Authenticate and Get the Token:
curl -X POST "URL" -H "accept: /" -H "Content-Type: application/x-www-form-urlencoded" -d "username=user&password=password"
result is:
enter image description here
<payloadFactory media-type="x-www-form-urlencoded">
<format>
{
"username":"user",
"password":"password"
}
</format>
<args>
</args>
</payloadFactory>
<header name="Content-Type" value="application/x-www-form-urlencoded" scope="transport" />
<property name="messageType" value="application/json" scope="axis2" type="STRING" />
<property name="REST_URL_POSTFIX" value="" scope="axis2" type="STRING" />
<call blocking="true">
<endpoint>
<http method="POST" uri-template="URL" />
</endpoint>
</call>
<property name="bearer-token" expression="json-eval($..token)" scope="default" type="STRING" />
<property name="REST_URL_POSTFIX" expression="get-property('resource')" scope="axis2" type="STRING" />
<header name="Authorization" expression="fn:concat('Bearer ', get-property('bearer-token'))" scope="transport" />
<payloadFactory media-type="x-www-form-urlencoded">
<format>$1</format>
<args>
<arg evaluator="xml" expression="get-property('request-body')" />
</args>
</payloadFactory>
But i have this error:
enter image description here
WSO2 API Manager Logs
INFO - LogMediator STATUS = Message dispatched to the main sequence. Invalid URL., RESOURCE = url, HEALTH CHECK URL = url
[2021-07-28 16:22:39,696] INFO - LogMediator STATUS = Message dispatched to the main sequence. Invalid URL., RESOURCE = url, HEALTH CHECK URL = url
Make sure that, you have provided the correct token endpoint url for the Call mediator
<call blocking="true">
<endpoint>
<http method="POST" uri-template="https://your-token-endpoint/oauth" />
</endpoint>
</call>
In call mediator we can form endpoint using XPath (from the response).But the problem is endpoint is not calling.
<?xml version="1.0" encoding="UTF-8"?>
<api context="/xpath" name="call"
xmlns="http://ws.apache.org/ns/synapse">
<resource methods="GET" protocol="http">
<inSequence>
<call>
<endpoint key-expression="/root/a"/>
</call>
<respond/>
</inSequence>
<outSequence/>
<faultSequence/>
</resource>
</api>
following response is from postman.
<root>
<a>http://www.mocky.io/v2/5ca6db71340000132f76b192</a>
</root>
Expected response :
<root>
<name>abcd</name>
<no>82382832</no>
</root>
Firstly, when using the resolving endpoint (using key-expression), we cannot give the URL directly [1]. We have to have the endpoint defined beforehand and should give only the key of the endpoint in the payload.
Secondly, for the key-expression to parse the xpath, the message should be built beforehand. Since call mediator is content-unaware, it will not build the message. Therefore, we should use a content aware mediator to build the message.
Following is the sample inSequence that'd work.
<inSequence>
<log level="full"/>
<call>
<endpoint key-expression="//a"/>
</call>
<respond/>
</inSequence>
Now the payload should be like
<root>
<a>testEndpoint</a>
</root>
Edit:
The endpoint named 'testEndpoint' should be defined with the backend url.
You need to define an endpoint [2]. For example, I'm using an address endpoint.
<endpoint xmlns="http://ws.apache.org/ns/synapse" name="testEndpoint">
<address uri="http://www.mocky.io/v2/5ca6db71340000132f76b192">
<suspendOnFailure>
<progressionFactor>1.0</progressionFactor>
</suspendOnFailure>
<markForSuspension>
<retriesBeforeSuspension>0</retriesBeforeSuspension>
<retryDelay>0</retryDelay>
</markForSuspension>
</address>
</endpoint>
Try this. I receieved needed response in Postman, but you should use POST method as your request has a Body.
<api xmlns="http://ws.apache.org/ns/synapse" name="call" context="/xpath">
<resource methods="POST">
<inSequence>
<property name="uri.var.httpendpointurl" expression="$body/root/a" scope="default" type="STRING"/>
<call>
<endpoint>
<http uri-template="{uri.var.httpendpointurl}"/>
</endpoint>
</call>
<respond/>
</inSequence>
<outSequence/>
<faultSequence/>
</resource>
</api>
I am getting below error while calling http endpoint:-
The endpoint is HTTP endpoint which I am using.
Also added timeout parameters in axis2.xml and axis2.blocking.xml.
But it did not work.
Can anyone provide any solution to it?
HTTPSender Unable to sendViaPost to url[http://*********]
org.apache.commons.httpclient.NoHttpResponseException: The server ****** failed to respond
at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1976)
at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098)
the esb proxy looks like below:--
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="mqListener"
startOnLoad="true"
statistics="disable"
trace="disable"
transports="http,https">
<target>
<inSequence>
<log description="print message" level="full">
<property name="message" value=""In listenAbc1Mq""/>
</log>
<payloadFactory media-type="json">
<format>
{
"orderId": ""
}
</format>
<args>
<arg evaluator="xml" expression="//verkkopvc/text()"/>
</payloadFactory>
<log description="print message" level="full">
<property name="message" value=""after payload factory""/>
</log>
<property name="OUT_ONLY" value="true"/>
<property name="DISABLE_CHUNKING"
scope="axis2"
type="STRING"
value="true"/>
<call blocking="true">
<endpoint key="abc"/>
</call>
<log description="print message" level="full">
<property name="message" value=""Out sequence""/>
</log>
</inSequence>
<outSequence/>
<description/>
</proxy>
I believe the error is printed by your http client. To fix it, do these.
1) Remove <property name="OUT_ONLY" value="true"/>
2) Add <respond/> mediator at the end of inSequence.
Hi I have an API with a custom sequence (dblookup & switch sequence) that will verify if a user is existing on the database, if not it should send a http status 401: Unauthorized, below is the case code but I always get an error cannot infer the transport information. What is the correct way of sending the back the response message.
THanks,
Drew
<case regex="0">
<log level="custom">
<property name="ucount" expression="fn:concat('User login - ', get-property('employee_count'))"/>
</log>
<send>
<property name="RESPONSE" value="true" scope="default"/>
<property name="NO_ENTITY_BODY" action="remove" scope="axis2"/>
<property name="HTTP_SC" value="401" scope="axis2"/>
<header name="To" action="remove"/>
<payloadFactory media-type="xml">
<format>
<response>
<result>Unauthorized</result>
</response>
</format>
<args/>
</payloadFactory>
<send/>
</case>
ERROR:
TID: [0] [AM] [2014-12-02 08:16:30,852] ERROR {org.apache.synapse.core.axis2.Axis2Sender} - Unexpected error during sending message out {org.apache.synapse.core.axis2.Axis2Sender}
org.apache.axis2.AxisFault: The system cannot infer the transport information from the /devtest/1.0/users/admin URL.
at org.apache.axis2.description.ClientUtils.inferOutTransport(ClientUtils.java:81)
at org.apache.synapse.core.axis2.DynamicAxisOperation$DynamicOperationClient.executeImpl(DynamicAxisOperation.java:115)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
at org.apache.synapse.core.axis2.Axis2FlexibleMEPClient.send(Axis2FlexibleMEPClient.java:482)
at org.apache.synapse.core.axis2.Axis2Sender.sendOn(Axis2Sender.java:59)
at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.send(Axis2SynapseEnvironment.java:338)
at org.apache.synapse.mediators.builtin.SendMediator.mediate(SendMediator.java:94)
at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:77)
at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:47)
at org.apache.synapse.config.xml.AnonymousListMediator.mediate(AnonymousListMediator.java:30)
at org.apache.synapse.config.xml.SwitchCase.mediate(SwitchCase.java:66)
at org.apache.synapse.mediators.filters.SwitchMediator.mediate(SwitchMediator.java:123)
at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:77)
at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:47)
at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:131)
at org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.mediate(APIManagerExtensionHandler.java:64)
at org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.handleRequest(APIManagerExtensionHandler.java:180)
at org.apache.synapse.rest.API.process(API.java:285)
at org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:83)
at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:64)
at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:220)
at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:83)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:344)
at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:168)
at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
TID: [0] [AM] [2014-12-02 08:16:30,853] INFO {org.apache.synapse.mediators.builtin.LogMediator} - STATUS = Executing default 'fault' sequence, ERROR_CODE = 0, ERROR_MESSAGE = Unexpected error during sending message out {org.apache.synapse.mediators.builtin.LogMediator}
Within send mediator you can not define other mediators.
Correct like this;
<property name="RESPONSE" value="true" scope="default"/>
<property name="NO_ENTITY_BODY" action="remove" scope="axis2"/>
<property name="HTTP_SC" value="401" scope="axis2"/>
<header name="To" action="remove"/>
<payloadFactory media-type="xml">
<format>
<response>
<result>Unauthorized</result>
</response>
</format>
<args/>
</payloadFactory>
<send>
endpoint>
<address uri="ADDRESS OF YOUR ENDPOINT"/>
</endpoint>
</send>
In my case there were invisible characters prepended to otherwise correct (Production/Sandbox) URL.
WSO2 seems very strict and didn't manage to interpret such definition, resulting in vague error:
The system cannot infer the transport information from the https://...
Notice the two spaces between the and https. It may have been a tabulator character.
We have spring security oauth2 based application. Every thing is working fine. But i am failed to change default token endpoint from "/oauth/token" to "/external/oauth/token".
My spring-servlet.xml
<http pattern="/external/oauth/token" create-session="stateless"
authentication-manager-ref="clientAuthenticationManager"
use-expressions="true" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/external/oauth/token" access="isFullyAuthenticated()" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<!-- include this only if you need to authenticate clients via request parameters -->
<custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>
<oauth:authorization-server client-details-service-ref="clientDetails"
token-services-ref="tokenServices"
user-approval-handler-ref="userApprovalHandler" token-endpoint-url="/external/oauth/token">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password />
</oauth:authorization-server>
But the result when i access this endpoint is
{
error: "unauthorized"
error_description: "An Authentication object was not found in the SecurityContext"
}
am i missing any thing ? Please suggest.
With the version 2.0.5.RELEASE or above of spring-security-oauth2
In one line in java based configuration, tested and works fine, somehow it's overriding the RequestMapping value of the TokenEndpoint class.
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.pathMapping("/oauth/token", "<your custom endpoint>")
}
}
Just struggled with this for a few days, but have it working now on latest Spring Oauth2 1.0.5.RELEASE. I'm not 100% sure my solution is the classiest (Step 4 in particular), but it works and I'm able to move forward.
In my case, I wanted to remove the /oauth prefix from the urls to end up with just /token and /authorize. The solution for me was mostly xml config, with two hacks to override endpoint request mappings.
1 - In app context xml, add authorization-endpoint-url and token-endpoint-url attribs to your <oauth:authorization-server> element.
Mine:
<oauth:authorization-server client-details-service-ref="clientDetailsService" token-services-ref="tokenServices" user-approval-handler-ref="userApprovalHandler" authorization-endpoint-url="/authorize" token-endpoint-url="/token">
2 - In app context xml, adjust the security endpoints accordingly. There should be two, which respectively manage security on the token and auth urls. Need to update the pattern prop on <http> and <intercept-url> tags.
Mine:
<http pattern="/token/**" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/token/**" access="IS_AUTHENTICATED_FULLY" />
...
<http pattern="/authorize/**" access-denied-page="/login.jsp?authorization_error=true" disable-url-rewriting="true" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/authorize/**" access="IS_AUTHENTICATED_FULLY" />
3 - (If you chose to employ the optional clientCreds filter.) In app context xml, you should already have wired-in the clientCredentialsTokenEndpointFilter bean as a <custom-filter> within yourelement. So, within the filter's bean, add afilterProcessesUrl` property.
Mine:
<bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
<property name="filterProcessesUrl" value="/token" />
</bean>
4 - The last step is to override the request mapping urls of the actual internal endpoint controllers. The spring oauth2 lib comes with two classes: AuthorizationEndpoint and TokenEndpoint. Each use #RequestMapping type annotations to bind the url (as we all do for our projects' app controllers). For me, it was a hair-pulling effort to attempt to override the value of the request mappings in any way other than to (sadly) recreate the spring class package in my src folder, copy the AuthorizationEndpoint and TokenEndpoint classes verbatim into said folder, and edit the inline #RequestMapping annotation values.
Anyway, that does the trick. Would love to hear of a more graceful way to override the endpoint controller request mapping values.
Thanks.
Final, working app context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:sec="http://www.springframework.org/schema/security" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.xsd
"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>
<!-- Declare OAuth2 services white-list. (This is the top of the config.) -->
<oauth:authorization-server client-details-service-ref="clientDetailsService" token-services-ref="tokenServices" user-approval-handler-ref="userApprovalHandler" authorization-endpoint-url="/authorize" token-endpoint-url="/token">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<!-- <oauth:password /> -->
</oauth:authorization-server>
<bean id="userApprovalHandler" class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
<!-- This bean bridges client auth service and user tokens... kind of an out of place requirement. -->
<property name="tokenServices" ref="tokenServices" />
</bean>
<!-- This starts the far back-end config for client token management. -->
<sec:authentication-manager id="clientAuthenticationManager">
<sec:authentication-provider user-service-ref="clientDetailsUserService" />
</sec:authentication-manager>
<bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetailsService" />
</bean>
<bean id="clientDetailsService" class="com.mycompany.oauth.spring.security.oauth2.IntegratedOauth2ClientDetailsService">
<!-- This bean is what wires OAuth2 into the persistence stack for client details stored in the oauth_client table. -->
</bean>
<!-- OAuth is layered on to spring security which is centered around users which requires a user auth manager. -->
<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
<authentication-provider ref="daoAuthenticationProvider" />
</authentication-manager>
<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetailsService" />
</bean>
<bean id="tokenStore" class="com.mycompany.oauth.spring.security.oauth2.IntegratedOAuth2TokenStore">
<!-- This bean is what wires OAuth2 tokens into my company's application stack. -->
<constructor-arg ref="dataSource" />
</bean>
<!-- **************************************************************************************** -->
<!-- Finally, sew OAuth into spring security with some http tags... -->
<!-- **************************************************************************************** -->
<!-- The OAuth2 endpoint for direct token requests (i.e. for client_credentials flow). -->
<http pattern="/token/**" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/token/**" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
<property name="filterProcessesUrl" value="/token" />
</bean>
<bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="myrealm" />
</bean>
<bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<!-- The OAuth2 endpoint for user-approved authorization (i.e. for "authorization" flow involving user login/approve). -->
<http pattern="/authorize/**" access-denied-page="/login.jsp?authorization_error=true" disable-url-rewriting="true" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/authorize/**" access="IS_AUTHENTICATED_FULLY" />
<form-login authentication-failure-url="/login.jsp?authentication_error=true" default-target-url="http://www.mycompany.com/" login-page="/login.jsp" login-processing-url="/login.do" />
<http-basic />
<anonymous />
</http>
</beans>
For customize the token end point URL, do the following steps.
1) Write your own class that extends ClientCredentialsTokenEndpointFilter class & call ClientCredentialsTokenEndpointFilter class constructor with "/external/oauth/token" value.
super("/external/oauth/token");
2) Plug your new customize filter in security configuration.
Replace
<custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
with
<custom-filter ref="your customize filter" after="BASIC_AUTH_FILTER" />
3) Create your own class for new mapping (/external/oauth/token) & extend tokenendpoint.
4) Change http & intercept-url element's pattern attribute value to "/external/oauth/token"
You are making this harder than what it should be, it's actually very simple !
(Notice I'm using "oauth2:" instead of "oauth:" as the XML tag)
Go to your security-context.xml
Find "oauth2:authorization-server" in the above file.
<oauth2:authorization-server
client-details-service-ref="someService"
request-validator-ref="someScopeRequestValidator"
token-services-ref="someTokenServices" >
Just add token-endpoint-url="/oauth/whatever_you_like"
<oauth2:authorization-server
client-details-service-ref="someService"
request-validator-ref="someScopeRequestValidator"
token-services-ref="someTokenServices"
**token-endpoint-url="/oauth/whatever_you_like"** >