简体   繁体   中英

Unable to set the custom response code in class mediator and xml wso2 apim 3.2.0

I have used a java class mediator in the custom sequence(xml) where I process the request payload and check whether the user is valid or not.

If the user is valid, the request will be sent to the backend.

But, if the user is invalid, the request should not be sent to the backend and the response code needs to be set via java class mediator or the custom sequence(xml). Currently I am receiving 202 Accepted I need to override the status code to 401.

In the java class mediator, I have used the below lines for setting the property.

org.apache.axis2.context.MessageContext msgContext = ((Axis2MessageContext) mc).getAxis2MessageContext();
msgContext.setProperty("HTTP_SC", "401"); 
//msgContext.setProperty("HTTP_SC", 401); (tried without quotes 401 too!!)
//mc.setProperty("HTTP_SC", 401);
((Axis2MessageContext) mc).setAxis2MessageContext(msgContext);

I tried via custom sequence(xml) using below lines,

<property action="remove" name="HTTP_SC" scope="axis2"/>
<property name="SC_ACCEPTED" scope="axis2" value="false"/>
<property name="HTTP_SC" scope="axis2" value="401"/>
<send/>

In both cases the 401 is not returned, 202 is only returned..

Suggest a way to to do it either in the class mediator or in the custom sequence.

You can try the following mediation

<api xmlns="http://ws.apache.org/ns/synapse" name="test" context="/test">
    <resource methods="GET">
        <inSequence>
            <property name="HTTP_SC" scope="axis2" value="409"/>
            <respond/>
        </inSequence>
        <outSequence/>
        <faultSequence/>
    </resource>
</api>
curl -is http://localhost:8280/test

HTTP/1.1 401 Unauthorized

You can test it or play with it using the following Dockerfile

FROM wso2/wso2am:3.2.0

COPY test.xml ${WSO2_SERVER_HOME}/repository/deployment/server/synapse-configs/default/api/test.xml

EXPOSE 8280
docker build -t test .
docker run --rm --name test -it -p 8280:8280 test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM