首页 > 解决方案 > 我如何使用弹簧上下文在 Zuul 过滤器之间传递新对象?

问题描述

目前,我已经AuthFilter在这里收到了一个UserState. 我需要将它传递给下一个过滤器。但是怎么做才对呢?还是存在其他解决方法?

public class AuthFilter extends ZuulFilter {

    @Autowired
    private AuthService authService;

    @Autowired
    private ApplicationContext appContext;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 2;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        String requestURI = context.getRequest().getRequestURI();
        for (String authPath : authPaths) {
            if (requestURI.contains(authPath)) return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {

        try {
            UserState userState = authService.getUserData();

            DefaultListableBeanFactory context = new DefaultListableBeanFactory();

            GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
            beanDefinition.setBeanClass(UserState.class);
            beanDefinition.setPropertyValues(new MutablePropertyValues() {
                {
                    add("user", userState);
                }
            });
            context.registerBeanDefinition("userState", beanDefinition);
        } catch (UndeclaredThrowableException e) {
            if (e.getUndeclaredThrowable().getClass() == UnauthorizedException.class) {
                throw new UnauthorizedException(e.getMessage());
            }

            if (e.getUndeclaredThrowable().getClass() == ForbiddenException.class) {
                throw new ForbiddenException(e.getMessage(), "The user is not allowed to make this request");
            }
        }

        return null;
    }
}

标签: springspring-cloudnetflix-zuul

解决方案


我很确定过滤器被链接在一起,请求/响应通过它们传递。您可以将数据添加到请求中,并让下一个过滤器查找它。


推荐阅读