it绿萝 - 云代码空间
——
public class AuthResponseFilter extends AbstractZuulFilter { private static final String RESPONSE_KEY_TOKEN = "token"; @Value("${system.config.authFilter.authUrl}") private String authUrl; @Value("${system.config.authFilter.tokenKey}") private String tokenKey = RESPONSE_KEY_TOKEN; @Autowired private AuthApi authApi; @Override public boolean shouldFilter() { RequestContext context = getCurrentContext(); return StringUtils.equals(context.getRequest().getRequestURI().toString(), authUrl); } @Override public Object run() { try { RequestContext context = getCurrentContext(); InputStream stream = context.getResponseDataStream(); String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8")); if (StringUtils.isNotBlank(body)) { Gson gson = new Gson(); @SuppressWarnings("unchecked") Map<String, String> result = gson.fromJson(body, Map.class); if (StringUtils.isNotBlank(result.get(tokenKey))) { AuthModel authResult = authApi.encodeToken(result.get(tokenKey)); if (authResult.getStatus() != HttpServletResponse.SC_OK) { throw new IllegalArgumentException(authResult.getErrMsg()); } String accessToken = authResult.getToken(); result.put(tokenKey, accessToken); } body = gson.toJson(result); } context.setResponseBody(body); } catch (IOException e) { rethrowRuntimeException(e); } return null; } @Override public String filterType() { return FilterConstants.POST_TYPE; } @Override public int filterOrder() { return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 2; } }
system.config.authFilter.authUrl=/user/login system.config.authFilter.tokenKey=token context.setResponseBody(body)
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try { init((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse); try { preRouting(); } catch (ZuulException e) { error(e); postRouting(); return; } // Only forward onto to the chain if a zuul response is not being sent if (!RequestContext.getCurrentContext().sendZuulResponse()) { filterChain.doFilter(servletRequest, servletResponse); return; } try { routing(); } catch (ZuulException e) { error(e); postRouting(); return; } try { postRouting(); } catch (ZuulException e) { error(e); return; } } catch (Throwable e) { error(new ZuulException(e, 500, "UNCAUGHT_EXCEPTION_FROM_FILTER_" + e.getClass().getName())); } finally { RequestContext.getCurrentContext().unset(); } }