我正在使用 Spring 微服务构建微服务,我有 2 个与此相关的问题。
1.我在 Api Gateway 即Zuul 服务器中有 spring 安全性,如果我已经从流中读取了一次请求以进行身份验证(从 POST 请求获取用户名/传递),现在 Zuul 不会转发任何请求我
new ObjectMapper().readValue(request.getInputStream(), UserDto.class);
如何读取请求然后再次将相同的请求转发给下游服务?
2. Zuul 没有将request.setAttribute()转发到下游服务,所以一个解决方法是使用ctx.addZuulRequestHeader,它Request Header
太大了,我怎样才能实现request.setAttribute并进入下游服务。
public Authentication getAuthentication(HttpServletRequest request) {
final String token = request.getHeader(AUTH_HEADER_NAME);
logger.info("token="+token);
if (token != null) {
logger.info("Entering getAuthentication");
final UserToken userInfo = tokenHandler.validateToken(token);
if (userInfo != null
&& token.equals(String.valueOf(redisUtility.getValue(userInfo.getUsername()+"_"+userInfo.getUniqueId())))) {
logger.info("Validating token key="+userInfo.getUsername()+"_"+userInfo.getUniqueId());
User user=userDetailsService.loadUserByUsername(userInfo.getUsername());
if(user!=null && user.getUsername().equals(userInfo.getUsername())
&& user.getLastPasswordResetTime()<userInfo.getCreatedTime()){
request.setAttribute("username",user.getUsername());//**Not able to fetch this in Downstream services**
logger.info("Token Authenticated for User "+user.getUsername());
return new UserAuthentication(user);
}
}
}
return null;
}
public class SimpleFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(SimpleFilter.class);
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
request.setAttribute("test", "test");// Not able to get this in services
log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
return null;
}
@Bean
public SimpleFilter simpleFilter() {
return new SimpleFilter();
}
@RequestMapping(value = "/test/avl",method=RequestMethod.POST)
public String test(HttpServletRequest request) {
System.out.println(request.getAttribute("test")+"");
return "Spring in Action";
}