在 Spring Cloud Gateway 中禁止未经身份验证的请求 [英] Forbid Unauthenticated requests in Spring Cloud Gateway
本文介绍了在 Spring Cloud Gateway 中禁止未经身份验证的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 spring cloud gateway 中实现了自定义预过滤器,它允许经过身份验证的请求通过下游进程.我想要的是,如果请求未经身份验证,则返回 401 UNAUTHORIZE 状态的响应并停止下游处理.能不能实现这个spring cloud gateway.
I have implemented custom pre filter in spring cloud gateway which allows authenticated requests to go through the downstream process. What I want is if the request is unauthenticated then return with response of 401 UNAUTHORIZE status and stop the downstream processing. Can I achieve this spring cloud gateway.
请帮忙.
我的过滤器代码如下
public class ValidUserFilter implements GatewayFilterFactory {
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
if (isValidRequest(request)) {
// Allow processing
} else {
// set UNAUTHORIZED 401 response and stop the processing
}
return chain.filter(exchange);
};
}
}
和配置如下:
- id: myroute
uri: http://localhost:8080/bar
predicates:
- Path=/foo/**
filters:
- ValidUserFilter
推荐答案
查看SetStatusGatewayFilterFactory
// set UNAUTHORIZED 401 response and stop the processing
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
这篇关于在 Spring Cloud Gateway 中禁止未经身份验证的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文