简体   繁体   中英

How can I get the client IP address of requests in Spring Boot?

I'm having trouble with my security configuration and I need to create a list of the Ip's that are accessing my application.

My problem is to get the Ip in a dynamic way for all my application requests. But I don't want to add a HttpServletRequest for all the requests of my application, what I want is a method that is called before every request, even before SecurityConfig events.

What I've tried to do is to use AuthenticationProvider to get the request HttpServletRequest and then get the Ip of my client. The problem is that I can't find a way to create a single class and it connects to all my requests. This is my code:

public abstract class IPAddressBasedAuthenticationProvider implements AuthenticationProvider {

  /**
   * Context http request
   */
  @Autowired
  private HttpServletRequest request;

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {

      String ipAddress = request.getRemoteAddr();
      System.out.println(ipAddress);
      return authentication;
  }
}

What I was thinking was that my requests where going to pass in this code and then show my client Ip.

I tried autowiring it in my controller classes but my application doesn't execute then. What can I do to make this work?

I've used a different way to get the addresses of my client requests.

I've created a class called WebConfig that implements WebMvcConfigurer. This class configures some usages in spring. and here's the code for this class:

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggerInterceptor());
    }
}

This method is registering an interceptor, this interceptor will intercept the requests and using methods you will create it will execute when some request is send. For exemple my code:

public class LoggerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {

        System.out.println(request.getRemoteAddr());
        return true;
    }
}

In my case I've used "preHandle" method to get the Ip of my client request, this method is called every time someone calls my application via request and before spring handles the request my method is called, it can be used as a security configuration as well, because you can return false, in that case the request won't execute. But for that usage there's others ways with spring boot.

If I'm doing something wrong please correct me.

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