[ 설정파일 ]
spring:
cloud:
gateway:
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_UNIQUE
- name: GlobalFilter
args:
baseMessage: Base Message
preLogger: true
postLogger: true
globalcors:
corsConfigurations:
'[/**]':
add-to-simple-url-handler-mapping: true
allowedOrigins:
- http://localhost:8081
allow-credentials: true
allowedMethods:
- GET
- POST
- DELETE
- PUT
- OPTIONS
routes:
- id: service1
uri: http://localhost:8080
predicates:
- Path=/api/service1/**
- id: service2
uri: http://localhost:8082
predicates:
- Path=/api/service2/**
filters:
- AddRequestHeader=META-TOKEN, A1B2C3D4E5
- RewritePath=/api/service2/(?<segment>/?.*), /api/$\{segment} # /api/service2/auth/login -> /api/auth/login
[ Global Filter ]
@Component
public class GlobalFilter extends AbstractGatewayFilterFactory<GlobalFilter.Config> {
@Autowired
private JwtProvider jwtProvider;
public GlobalFilter() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return (((exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
// is exist token
if (!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
return onError(exchange, "Not found authorization header");
}
// validate token
String authorization = Objects.requireNonNull(request.getHeaders().get(HttpHeaders.AUTHORIZATION)).get(0);
String token = authorization.replace("Bearer", "").trim();
if (!jwtProvider.isValidToken(token)) {
return onError(exchange, "JWT is not valid");
}
return chain.filter(exchange);
}));
}
private Mono<Void> onError(ServerWebExchange exchange, String message) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
@Data
public static class Config {
private String baseMessage;
private boolean preLogger;
private boolean postLogger;
}
}
'개발 > Java' 카테고리의 다른 글
[Spring] JWT Provider (0) | 2022.06.24 |
---|---|
스프링 배치 에러 (The injection porint has the following annotations) (0) | 2020.12.03 |
스프링 배치 동작 에러 (Failed to execute CommandLineRunner) (0) | 2020.09.16 |