Zuul 网关做token权限验证
zuul 传递请求头
@Component public class WebFilter extends ZuulFilter { @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { //得到request上下文 RequestContext currentContext = RequestContext.getCurrentContext(); //得到request域 HttpServletRequest request = currentContext.getRequest(); //得到头信息 String header = request.getHeader("Authorization"); //判断是否有头信息 if(header!=null && !"".equals(header)){ //把头信息继续向下传 currentContext.addZuulRequestHeader("Authorization", header); } return null; } }
做权限验证
@Component public class ManagerFilter extends ZuulFilter { @Autowired private JwtUtil jwtUtil; /** * 在请求前pre或者后post执行 * @return */ @Override public String filterType() { return "pre"; } /** * 多个过滤器的执行顺序,数字越小,表示越先执行 * @return */ @Override public int filterOrder() { return 0; } /** * 当前过滤器是否开启true表示开启 * @return */ @Override public boolean shouldFilter() { return true; } /** * 过滤器内执行的操作 return 任何ojbect的值都表示继续执行 * setsendzullRespponse(false)表示不再继续执行 * @return * @throws ZuulException */ @Override public Object run() throws ZuulException { System.out.println("经过后台过滤器了!"); RequestContext requestContext = RequestContext.getCurrentContext(); //request域 HttpServletRequest request = requestContext.getRequest(); if(request.getMethod().equals("OPTIONS")){ //预请求 放行 return null; } if(request.getRequestURI().indexOf("login")>0){ //登录请求放行 return null; } //得到头信息 String header = request.getHeader("Authorization"); if(header!=null && !"".equals(header)){ if(header.startsWith("Bearer ")){ String token = header.substring(7); try { Claims claims = jwtUtil.parseJWT(token); String roles = (String) claims.get("roles"); if(roles.equals("admin")){ //把头信息转发下去,并且放行 requestContext.addZuulRequestHeader("Authorization", header); return null; } }catch (Exception e){ e.printStackTrace(); requestContext.setSendZuulResponse(false);//终止运行 } } } requestContext.setSendZuulResponse(false);//终止运行 requestContext.setResponseStatusCode(403); requestContext.setResponseBody("权限不足"); requestContext.getResponse().setContentType("text/html;charset=utf-8"); return null; } }