imoteb imoteb - 4 months ago 20
Java Question

How to get IP address of incoming request SOAP

I have the following classes, how I can get the IP address of the incoming request source? I have checked several solutions on the internet but could not find some suitable one, if you need more information about the project structure I can add, thanks

@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {

@Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}

@Bean(name = "doSomething")
public DefaultWsdl11Definition defaultValidateWsdl11Definition(XsdSchema validateSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("ValidatePort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://www.org.com/validate");
wsdl11Definition.setSchema(validateSchema);
return wsdl11Definition;
}

@Bean(name = "doSecond")
public DefaultWsdl11Definition defaultActionWsdl11Definition(XsdSchema actionSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("ActionPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://www.org.com/action");
wsdl11Definition.setSchema(actionSchema);
return wsdl11Definition;
}

@Bean
public XsdSchema validateSchema() {
return new SimpleXsdSchema(new ClassPathResource("doSomething.xsd"));
}

@Bean
public XsdSchema actionSchema() {
return new SimpleXsdSchema(new ClassPathResource("doSecond.xsd"));
}

}
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://www.org.com/doSomething"
targetNamespace="http://www.org.com/doSomething" elementFormDefault="qualified">

<xs:element name="getActionRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="Username" type="xs:string"/>
<xs:element name="Password" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="getDoSomethingResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="Code" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>

Answer

As inidicated by Tibrogargan, it should be in the headers. You could get your Request injected like this

@Autowired
private HttpServletRequest request;

and get the IP address like this

protected String getIpAddress() {
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    return ipAddress;
}

You may have a chance to get IP address of the original sender with the X-FORWARDED-FOR header if not obscured by a proxy. Otherwise the getRemoteAddr() should do it.