application.yml用于Spring Cloud Gateway应用程序。
使用两个过滤器,第一个检查请求中的授权标头,第二个检查该yaml中指定的角色。
spring:
application:
name: MultipleFilters
cloud:
gateway:
routes:
- id: meterset
uri: http://localhost:9000/meterset
predicates:
- Path=/meterset
filters:
- name: AuthenticationFilter
- name: RoleFilter
args:
role1: editor
role2: viewer
自定义网关过滤器,用于根据yaml中指定的角色检查是否允许请求。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Component
public class RoleFilter implements GatewayFilterFactory<RoleFilter.Config> {
private static final String VALUE = "value";
@Override
public GatewayFilter apply(Config config) {
// exchange holds request, response and other server related Properties
return (exchange, chain) -> {
// get the request
ServerHttpRequest request = exchange.getRequest();
return chain.filter(exchange);
};
}
// Edit the response on error
private Mono<Void> onError(ServerWebExchange exchange, String err, HttpStatus httpStatus) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(httpStatus);
return response.setComplete();
}
@Override
public List<String> shortcutFieldOrder() {
return Collections.singletonList(VALUE);
}
@Override
public Config newConfig() {
return new Config();
}
public static class Config {
private List<String> value;
private String role1;
private String role2;
public List<String> getValue() {
return value;
}
public void setValue(List<String> value) {
this.value = value;
}
public String getRole1() {
return role1;
}
public void setRole1(String role1) {
this.role1 = role1;
}
public String getRole2() {
return role2;
}
public void setRole2(String role2) {
this.role2 = role2;
}
}
}
我能够将各种争论作为键值对传递,有没有办法将参数指定为逗号分隔的值,例如 RoleFilter = viewer,编辑器