Springboot interface adds IP whitelist restrictions

Implementation process: custom interceptor - inject interceptor - obtain request IP - compare whether the IP is consistent - request return

Article background: The interface adds IP whitelist restrictions, and only specified IPs can access the project.

Implementation idea: Add an interceptor, intercept all requests of the project, obtain the requested network IP, and check whether the IP is in the whitelist. The whitelist is set in the database and stored in a table. If there is this IP in the table, proceed to the next step. If not, intercept the request and return to the client.

Implementation method: HandlerInterceptor+MySQL+Mybatis-plus

Customize the interceptor, create a class and implement the HandlerInterceptor interface to become an interceptor.

The HandlerInterceptor interface provides three methods, the three methods are as follows
preHandle method Called before the business processor processes the request, it can be used for permission verification, token verification, etc. The result returns true to continue execution, and the result returns false to intercept the request.
postHandle method Executed after the business processor processes the request and before generating the view.
afterCompletion method After the business processor is executed, it can be used to clean up resources, log records, and so on.

Custom interceptor: implement the HandlerInterceptor interface, rewrite the preHandle method, and add the method of obtaining IP and IP inspection service in preHandle. The testEngineerService.getIp() method involved in the code is below! ! !

import com.alibaba.fastjson.JSON;
import com.lifel.service.TestEngineer.TestEngineerService;
import com.lifel.utils.ToolsResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;

/********************************************************************************
 ** @author : ZYJ
 ** @date :2023/04/23
 ** @description :自定义拦截器 拦截ip
 *********************************************************************************/
@Slf4j
public class WhiteListIntercept implements HandlerInterceptor {

    @Autowired
    private TestEngineerService testEngineerService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        log.info("机主的ip是"+ipAddress);
        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        if(cxt != null && cxt.getBean(TestEngineerService.class) != null &&testEngineerService == null) {
            testEngineerService =cxt.getBean(TestEngineerService.class);
        }
        if(testEngineerService.getIp(ipAddress)){
            return true;
        }else{
            returnJson(response, JSON.toJSONString(new ToolsResultEntity(1002, "ip不存在", null)));
            return false;
        }
    }

    /********************************************************************************
     ** @author : ZYJ
     ** @date :2023/04/23
     ** @description :设置请求拦截返回参数
     *********************************************************************************/
    private void returnJson(HttpServletResponse response, String result) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);
        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}

Inject interceptors: inject interceptors into spring and hand them over to spring management

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class AdminWebConfig implements WebMvcConfigurer {

    /********************************************************************************
     ** @author : ZYJ
     ** @date :2023/04/23
     ** @description :配置拦截器
     *********************************************************************************/
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//       下面这句代码相当于添加一个拦截器,添加的拦截器就是我们刚刚创建的
        registry.addInterceptor(new WhiteListIntercept())
//       addPathPatterns()配置我们要拦截哪些路径 addPathPatterns("/**")表示拦截所有请求,包括我们的静态资源
                .addPathPatterns("/**");
    }
}

Create Service and implementation class


public interface TestEngineerService {

    /********************************************************************************
     ** @author : ZYJ
     ** @date :2023/04/23
     ** @description :查询IP是否在白名单中
     *********************************************************************************/
    Boolean getIp(String name);

}
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lifel.entity.TestEngineer.WhiteIp;
import com.lifel.mapper.TestEngineer.WhiteIpMapper;
import com.lifel.service.TestEngineer.TestEngineerService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class TestEngineerServiceImpl implements TestEngineerService {

    @Resource
    private WhiteIpMapper whiteIpMapper;

    /********************************************************************************
     ** @author : ZYJ
     ** @date :2023/04/23
     ** @description :查询IP是否在数据库中保存
     *********************************************************************************/
    @Override
    public Boolean getIp(String name) {
        try {
            //查询表中是否有此IP,并且状态是打开的状态
            WhiteIp whiteIp = whiteIpMapper.selectOne(new QueryWrapper<WhiteIp>().eq("name", name).eq("state", "open"));
            if(whiteIp==null){
                return false;
            }else{
                return true;
            }
        }catch (Exception e){
            return false;
        }
    }
}

Test code, create Controller, call method for testing

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api")
@Api(value = "测试类", tags = "测试类")
public class TestEngineerController {

    @GetMapping("/test")
    @ApiOperation(value = "测试IP白名单是否生效")
    public String test() {
        return "ok";
    }
}

Check our IP address and save it in the database to ensure that only our own IP can access the project interface

Save our correct IP in the table, start the project to access the test method, and the request result returns normally! ! !

A wrong IP is saved in the table, and the project access test method is started, and the request interception prompts that the IP does not exist! ! !

Note: localhost cannot be written during testing, it must be 127.0.0.1:8080,

           127.0.0.1 gets our local IP, and localhost gets 0:0:0:0:0:0:0:1

The purpose of the article: to protect our system from malicious attacks! That's the end of this article! ! !

Guess you like

Origin blog.csdn.net/second_place_zyj/article/details/130320957