首页 » 文章 » spring cloud gateway filter 返回401

注意点:不要再返回 chain.filter...,直接return response.setComplete,这样就返回401 了,否则就会继续网后面执行,可能会返回200了。笔者就犯了这个错误

 
  @Component
    public class Session2header extends AbstractNameValueGatewayFilterFactory {
    
        private static final Logger log = LoggerFactory.getLogger(GatewayFilterFactory.class);
    
    
    
        @Override
        public GatewayFilter apply(NameValueConfig config) {
            return (exchange, chain) -> {
    
        //get UID
        ...
                if (!isSucess) {
                    ServerHttpResponse response = exchange.getResponse();
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
    //                return chain.filter(exchange.mutate().response(response).build());
                }

                ServerHttpRequest request = exchange.getRequest().mutate()
                        .header("user_id", uid)
                        .build();
                return chain.filter(exchange.mutate().request(request).build());
            };
        }
    
        private String getUidFromRedis(String token) {
            return userClient.IdByToken(token);
        }
    }

添加新评论