首页
>
软件编程
>
java
> SpringCloud Webflux过滤器增加header传递
SpringCloud Webflux过滤器增加header传递方式
作者:低头确望水中月亮
这篇文章主要介绍了SpringCloud Webflux过滤器增加header传递方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
Webflux过滤器增加header传递
webflux 使用异步非阻塞的方式,传递Header还需要我们自己增加代码传递:
定义过滤器,便携下面的配置可以尝试一下header的传递到后面的服务中。
@Component
public class AuthorizationFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest mutatedRequest = exchange.getRequest().mutate().header(HttpHeaders.AUTHORIZATION, "Bearer " + authHeader).build();
ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
return chain.filter(mutatedExchange);
## Kotlin 的方式
@Component
class AuthorizationFilter : WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
val mutatedRequest = exchange.request.mutate().header(HttpHeaders.AUTHORIZATION, "Bearer $authHeader").build()
val mutatedExchange = exchange.mutate().request(mutatedRequest).build()
return chain.filter(mutatedExchange)
Webflux过滤器使用
下面是简单处理token的例子
@Component
@Order(value = 2)
public class AuthFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
//ServerHttpResponse response = exchange.getResponse();
String token = request.getHeaders().getFirst("token");
if(null == token){
/*http头中没有appKey,修改请求的目标url为/auth/error
request.mutate返回一个请求构建器(builder design pattern),path方法修改请求的url,build方法返回新的request
ServerHttpRequest authErrorReq = request.mutate().path("/auth/error").build();
//erverWebExchange.mutate类似,构建一个新的ServerWebExchange
ServerWebExchange authErrorExchange = exchange.mutate().request(authErrorReq).build();
return chain.filter(authErrorExchange);
} else{
return chain.filter(exchange);
webFlux将指定的错误信息通过json格式返回给前端