java 使用filter实现uri自定义鉴权【避免文件流丢失现象

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

import cn.com.cintel.auth.util.SpringContextUtil;
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");
            config = SpringContextUtil.getBean(YmlParameterConfig.class);
        }
    }

    @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_ips.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;
            }
            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();
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值