基于SpringSecutrity实现黑白名单请求过滤

文章目录

  • 编写filter
  • 工具类
  • 配置文件

编写filter

package com.dstz.security.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dstz.base.rest.util.IPUtils;
import com.dstz.security.IngoreChecker;

/**
 * 白名单过滤器
 * 白名单IP在 -> app-security.xml 配置
 */
public class WhiteIpFilter extends IngoreChecker implements Filter {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void destroy() {
    	
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getServletPath();
        if(!path.contains("/btw")) {  // 如果不是请求的对外接口,忽略
        	 chain.doFilter(request, response);
        }else {
        	  logger.debug("----- 验证该IP是否是白名单 - 开始 -------");
              // 获取ip地址
              String realIP = IPUtils.getRealIP(req);
              if(StringUtils.isNotBlank(realIP)) {
              	boolean isIngoreUrl = this.isIngores(realIP);
              	if (isIngoreUrl) {
              		logger.debug("该IP是白名单!");
                    chain.doFilter(request, response);
                } else {
                	logger.debug("该IP不存在白名单中!拒绝访问!");
                     response.getWriter().print("你没有操作该api的操作权限");
                }
              }else {
              	// 无法获取到ip
              	response.getWriter().print("没有获取到请求的ip地址");
              }
        }
      
    }
    
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

}

工具类

package com.dstz.base.rest.util;

import javax.servlet.http.HttpServletRequest;

public class IPUtils {
    /**
     * 获取用户真实IP地址,不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值
     *
     * @return ip
     */
    public static String getRealIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值,第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
//            System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
//            System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
//            System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
//            System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
//            System.out.println("getRemoteAddr ip: " + ip);
        }
        return ip;
    }
}

配置文件



    <security:http entry-point-ref="authenticationLoginEntry">
        <security:remember-me key="rememberPrivateKey"/>




		
        <security:custom-filter ref="whiteIpFilter" before="CAS_FILTER"/>

        

        <security:custom-filter before="FILTER_SECURITY_INTERCEPTOR" ref="securityInterceptor"/>
        <security:access-denied-handler ref="accessDeniedHandler"/>
        <security:headers>
			<security:frame-options policy="SAMEORIGIN"/>
		security:headers>
        <security:csrf disabled="true"/>
    security:http>

    <bean id="whiteIpFilter" class="com.dstz.security.filter.WhiteIpFilter">
     	<property name="ingores">
            <list>
            	 <value>192.168.31.164value>
                 <value>127.0.0.1value>
                 <value>localhostvalue>
                 <value>47.106.139.29value>
            list>
         property>
    bean>

你可能感兴趣的:(java)