public class WxJwtFilter implements Filter {
@Autowired
private IUcUserService userService;
@Autowired
RequestMappingHandlerMapping requestMappingHandlerMapping;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
LoginUserUtil.removeUser();
// LoginUserUtil.removeTenantId();
String tenantId = request.getHeader(Constants.MP_APP_ID_HEADER_NAME);
if (StringUtils.isNotEmpty(tenantId)){
LoginUserUtil.setCurrentTenantId(tenantId);
}
boolean isOk = false;
try {
RequiresAuthentication requiresAuthentication = null;
HandlerExecutionChain handlerExecutionChain = requestMappingHandlerMapping.getHandler(request);
Object object = null;
if (handlerExecutionChain != null){
object = handlerExecutionChain.getHandler();
}
if (object instanceof HandlerMethod){
HandlerMethod handler = (HandlerMethod) object;
requiresAuthentication = handler.getMethodAnnotation(RequiresAuthentication.class);
}
if (requiresAuthentication != null){
String token = request.getHeader(Constants.H5_TOKEN_HEADER_NAME);
if (StringUtils.isEmpty(token)){
token = request.getParameter(Constants.H5_TOKEN_HEADER_NAME);
}
if (StringUtils.isEmpty(token)){
toJsonResponse(servletResponse, ResponseUtil.unlogin());
}else {
log.info("用户token:{}", token);
try {
String userId = JwtHelper.getInstance().getSubjectFromToken(token);
UcUser user = userService.getById(Integer.parseInt(userId));
if (user != null){
LoginUserUtil.setCurrentUser(user);
isOk = true;
}
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
isOk = false;
}
if (isOk){
filterChain.doFilter(servletRequest, servletResponse);
}else {
toJsonResponse(servletResponse, ResponseUtil.unlogin());
}
}
}else {
filterChain.doFilter(servletRequest, servletResponse);
}
} catch (Exception e) {
throw new ServletException(e);
}
}
private void toJsonResponse(ServletResponse servletResponse, ResponseWrapper responseWrapper) {
try {
servletResponse.setContentType("application/json;charset=UTF-8");
JacksonUtil.getObjectMapper().writeValue(servletResponse.getOutputStream(), responseWrapper);
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/282890.html