package com.demo.netty.controller.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Base64;
@Slf4j
@Component
@CrossOrigin
public class JwtTokenFilter extends OncePerRequestFilter {
@Autowired
@Qualifier(“handlerExceptionResolver”)
private HandlerExceptionResolver resolver;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String header = request.getHeader("Content-Type");
if (!ObjectUtils.isEmpty(header) && !ObjectUtils.isEmpty(header)){
if (header.contains("application/json")){
CustomHttpServletRequestWrapper customHttpServletRequestWrapper = null;
try {
customHttpServletRequestWrapper = new CustomHttpServletRequestWrapper(request);
BufferedReader streamReader = new BufferedReader( new InputStreamReader(customHttpServletRequestWrapper.getInputStream(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null){
responseStrBuilder.append(inputStr);
}
String s2 = responseStrBuilder.toString();
JSONObject jsonObject = JSON.parseObject(s2);
String data = jsonObject.getString("data");
byte[] decode = Base64.getDecoder().decode(data);
String s = new String(decode);
customHttpServletRequestWrapper.setBody(s);
} catch (Exception e) {
e.printStackTrace();
}
filterChain.doFilter(customHttpServletRequestWrapper,response);
return;
}
}
filterChain.doFilter(request,response);
}
}