springboot 过滤器filter ,ip鉴权

前言:

已避免读request内容一次造成数据消失的问题

0:0:0:0:0:0:0:1是ipv6的表现形式,对应ipv4来说相当于127.0.0.1,也就是本机.如果项目部署在本机win7系统,访问时是通过 localhost 来访问,用java获取ip地址可能会出现该问题,这时获取的ip将是 0:0:0:0:0:0:0:1

正文:

  1. main函数添加注解 @ServletComponentScan
  2. 编写filter类
package cn.com.cintel.ims.lmn.common;

import cn.com.cintel.ims.lmn.common.utils.IpUtils;
import cn.com.cintel.ims.lmn.common.utils.rest.RequestUtil;
import cn.com.cintel.ims.lmn.config.YmlParameterConfig;
import cn.com.cintel.ims.lmn.domain.common.BaseResponse;
import cn.com.cintel.ims.lmn.domain.common.CommonAuthInfo;
import cn.com.cintel.ims.lmn.domain.common.CommonResInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @description: 鉴权
 * @author: hanxs
 * @date: 2020/03/10
 */
@Log4j2
//@Component
@WebFilter(urlPatterns = { "/IF/*"})
public class AuthFilter  implements Filter {


    @Autowired
    YmlParameterConfig config;

    static List<String> AUTH_BCN_IP_LIST;
    final static String NO_AUTH_URI="/IF/loadAudioTemplateResult";//语音模板上报不鉴权


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if(config==null) {
            ServletContext servletContext = filterConfig.getServletContext();
            ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            config = (YmlParameterConfig) ctx.getBean("ymlParameterConfig");
        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String index="1";
        String errText="";
        String requestURI=request.getRequestURI().replaceFirst(request.getContextPath(),"");

        if(NO_AUTH_URI.equals(requestURI)){
            log.info("不鉴权:"+requestURI);
        }else if("0".equals(config.auth_switch)){
            log.info("不鉴权,鉴权已关");
        }else{
            // 防止流读取一次后就没有了, 所以需要将流继续写出去
            ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            String jsonString = HttpHelper.getBodyString(requestWrapper);

            if(AUTH_BCN_IP_LIST==null) {
                AUTH_BCN_IP_LIST = Arrays.asList(config.auth_bcn_ip.split(","));
            }
            //用户IP地址鉴权
            if(!AUTH_BCN_IP_LIST.contains(IpUtils.getIpAddr(request))){
                errText="IP地址鉴权,鉴权失败,此ip不在信任列表:"+IpUtils.getIpAddr(request);
            }else{
                //用户密码鉴权
//                String jsonString = RequestUtil.getRequest(request);
                log.info("uri:"+requestURI+" ] json:"+requestURI+jsonString);
                JSONObject jsonObject = JSON.parseObject(jsonString);

                CommonAuthInfo authInfo=jsonObject.getObject("authInfo", CommonAuthInfo.class);
                Map<String,String> reqInfo=jsonObject.getObject("reqInfo", Map.class);
                index=reqInfo.get("serialnumber");

                if(config.deliverClientid.equals(authInfo.getClientId())&&config.deliverPasswd.equals(authInfo.getPassWord())){
                    log.info("鉴权成功:"+index+":"+requestURI);
                }else{
                    errText="用户密码鉴权,鉴权失败";
                }
            }

            if(StringUtils.isNotEmpty(errText)){
                BaseResponse rstDomain = new BaseResponse();
                CommonResInfo resInfo = new CommonResInfo(index,"1",errText);
                rstDomain.setResInfo(resInfo);
                String string = JSON.toJSONString(rstDomain);

                System.out.println("- ->>http响应json" + string);
                response.setHeader("cache-control", "no-cache");
                response.setContentType("text/html");
//        response.setContentType("application/json");
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                PrintWriter pw = response.getWriter();
                pw.write(string);
                pw.flush();
                pw.close();

                return;
            }
//            req=requestWrapper;
            chain.doFilter(requestWrapper, res);
            return;

        }

        chain.doFilter(req, res);

    }

    @Override
    public void destroy() {
    }

}

class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }
}

class HttpHelper {

    /**
     * 获取请求Body
     *
     * @param request
     * @return
     */
    public static String getBodyString(ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

}

相关工具类

package cn.com.cintel.ims.lmn.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author
 * @since 2020/2/25 14:01
 */
public class IpUtils {
    public static String getIpAndPort(HttpServletRequest request) {
        String ipAddress = getIpAddr(request);
        int port =request.getRemotePort();//返回发出请求的客户机的端口号。
        ipAddress=ipAddress+":"+port;
        return  ipAddress;
    }
    public static String getIpAddr(HttpServletRequest request) {
        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")||*/ipAddress.equals("0:0:0:0:0:0:0:1")) {
                    // 根据网卡取本机配置的IP
//                    InetAddress inet = null;
//                    try {
//                        inet = InetAddress.getLocalHost();
//                    } catch (UnknownHostException e) {
//                        e.printStackTrace();
//                    }
//                    ipAddress = inet.getHostAddress();
                    ipAddress="127.0.0.1";
                }
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }

        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值