Reputation: 51
This is my first question here, I'm sorry if there is something wrong, please correct me).
I am working on a spring boot application with spring boot security.
I use RestController
for the creation of my API.
I need to log the IP address of all clients who try to access my API, even if they are not authenticated.
I can get the client's IP after authentication or when the client accesses to the public API by this (get from HttpServletRequest
):
@GetMapping("/api/public/getDeviceList")
public List<Device> getDeviceList(HttpServletRequest httpServletRequest) {
System.out.println(httpServletRequest.getRemoteHost());
}
But when the client accesses a private API with wrong credentials, I don't get these IP addresses.
How can I retrieve this information?
Upvotes: 2
Views: 14790
Reputation: 51
I get solution in adding custom filter in security chain. In this filter i can log all information i need. Create filter:
public class CustomSecurityFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
System.out.println("Enter custom filter");
System.out.println("method:"+request.getMethod() + "\nurl:"+request.getRequestURI()+"\nip address:"+request.getRemoteAddr());
filterChain.doFilter(servletRequest, servletResponse);
}
}
then add this filter in WebSecurityConfigurerAdapter in configure(HttpSecurity http) method
@Configuration
@EnableWebSecurity
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
http.csrf().disable().authorizeRequests()
.antMatchers("/api/private/**").authenticated()
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// -----Add new filter in chain-----
http.addFilterBefore(new CustomSecurityFilter(),
SecurityContextPersistenceFilter.class);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/public/**");
}
}
Upvotes: 2
Reputation: 324
The method getRemoteHost()
returns the name of the client system as a string.
The method getRemoteAddr()
returns the client's IP address that's accessing your Java web application
Try with this on your method controller
System.out.println(httpServletRequest.getRemoteAddr());
If your server is local it will return you 0:0:0:0:0:0:0:1
but if you test on another computer on your local network, the correct ip should be shown, for example 192.168.1.4
Upvotes: 4