Saya mencoba men-debug aplikasi saya, tetapi debugger tidak mengenai blok kode ini. Ini adalah filter gateway khusus saya.

@RefreshScope
@Component
public class AuthorizationHeaderFilter extends 
           AbstractGatewayFilterFactory<AuthorizationHeaderFilter.Config> {

@Autowired
Environment environment;

public AuthorizationHeaderFilter () {
    super(Config.class);
}

public static class Config {
}

@Override
public GatewayFilter apply(Config config) {
    return ((exchange, chain) -> {

        ServerHttpRequest request = exchange.getRequest();

        if(!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
            return onError(exchange, "No authorization header", HttpStatus.UNAUTHORIZED);
        }

        String token = Objects.requireNonNull(request.getHeaders().get(HttpHeaders.AUTHORIZATION))
                .get(0).replace("Bearer","");

        if(isJwtValid(token))
            return onError(exchange, "JWT Token is not valid", HttpStatus.UNAUTHORIZED);

        return chain.filter(exchange);
    });
}

private Mono<Void> onError(ServerWebExchange exchange, String error, HttpStatus status) {
    ServerHttpResponse response = exchange.getResponse();

    response.setStatusCode(status);
    return response.setComplete();
}

private boolean isJwtValid(String token) {
    boolean returnValue = true;

    String subject = Jwts.parser().setSigningKey(environment.getProperty("token.secret")).parseClaimsJws(token)
            .getBody().getSubject();

    if(subject == null || subject.isEmpty())
        returnValue = false;

    return returnValue;
}
}

Dan inilah konfigurasi untuk filter ini

spring.cloud.gateway.routes[0].id=users-status-check
spring.cloud.gateway.routes[0].uri=lb://users-ws
spring.cloud.gateway.routes[0].predicates[0]=Path=/users-ws/users/status
spring.cloud.gateway.routes[0].predicates[1]=Method=GET
spring.cloud.gateway.routes[0].predicates[2]=Header=Authorization, Bearer (.*)
spring.cloud.gateway.routes[0].filters[0]=RewritePath=/users-ws/(?<segment>.*), /${segment}
spring.cloud.gateway.routes[0].filters[1]=AuthorizationHeaderFilter

Saat mencoba mengirim permintaan, titik akhir ini tidak memulai debugger atau mencetak log ke konsol. Apa yang saya lewatkan di sini. Terima kasih.

Jika saya membuat kacang AuthorizationHeaderFilter di aplikasi utama saya seperti ini

@SpringBootApplication
public class ApiGatewayApplication {

   public static void main(String[] args) {
       SpringApplication.run(ApiGatewayApplication.class, args);
   }


   @Bean
   public AuthorizationHeaderFilter authorizationHeaderFilter() {
    return new AuthorizationHeaderFilter();
   }
}

Aplikasi melempar kesalahan ini saat startup

org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'authorizationHeaderFilter' defined in com.springcloud.photoapp.api.ApiGateway.ApiGatewayApplication: @Bean definition illegally overridden by existing bean definition: Root bean: class [org.springframework.aop.scope.ScopedProxyFactoryBean];

Saya juga mengatur level logging untuk men-debug gateway cloud api, ini lognya

 Mapping [Exchange: GET http://localhost:8764/users-ws/users/status] to 
 Route{id='ReactiveCompositeDiscoveryClient_USERS-WS', uri=lb://USERS-WS, 
 order=0, predicate=Paths: [/users-ws/**], match trailing slash: true, 
 gatewayFilters=[[[RewritePath /users-ws/(?<remaining>.*) = '/${remaining}'], 
 order = 1]], metadata={}}
 
 RouteDefinition users-status-check applying {_genkey_0=/users- 
 ws/users/status} to Path
 RouteDefinition users-status-check applying {_genkey_0=GET} to Method
 RouteDefinition users-status-check applying {_genkey_0=Authorization, 
 _genkey_1=Bearer (.*)} to Header
 RouteDefinition users-status-check applying filter {_genkey_0=/users-ws/(? 
 <segment>.*), _genkey_1=/${segment}} to RewritePath
 RouteDefinition users-status-check applying filter {} to 
 AuthorizationHeaderFilter
1
isadev41 9 Mei 2021, 18:50

1 menjawab

Jawaban Terbaik

Hai saya berhasil menyelesaikan masalah ini dengan membuat RouteLocator @Bean seperti di bawah ini. Sekarang ketika saya membuat permintaan dalam mode debugger saya dapat menekan metode apply di AuthorizationHeaderFilter

@SpringBootApplication
public class ApiGatewayApplication {

   public static void main(String[] args) {
       SpringApplication.run(ApiGatewayApplication.class, args);
   }

   @Bean
   public RouteLocator routeLocator(RouteLocatorBuilder rlb, AuthorizationHeaderFilter 
   authorizationHeaderFilter) {

       return rlb
               .routes()
               .route(p -> p
                   .path("/users-ws/users/status")
                   .filters(f -> f.removeRequestHeader("Cookie")
                           .rewritePath("/users-ws/(?<segment>.*)", "/$\\{segment}")
                           .filter(authorizationHeaderFilter.apply(new 
                            AuthorizationHeaderFilter.Config())))
                .uri("lb://users-ws")
            )
            .build();
     }
 }
0
Isa Toltar 10 Mei 2021, 15:48