4

I have been using spring cloud gateway along with spring security to protect my actuator endpoints and a custom gateway filter for authorization filtering. Below are the implementations I have made :

For Spring security I have used the following config :

@EnableWebFluxSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
       http.csrf().disable().authorizeExchange().pathMatchers("/actuator/**").authenticated().anyExchange().permitAll().and().httpBasic();
       return http.build();
    }
}

And my custom filter is like this:

@Component
public class AuthorizationRequestFilter implements GatewayFilterFactory<AuthorizationRequestFilter.Config>, Ordered {


@Override
public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
        ServerHttpRequest request = exchange.getRequest();
        String authToken = request.getHeaders().getFirst("Authorization");
        if (StringUtils.isEmpty(authToken)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            byte[] response =  "{\"status\":\"401\",\"message\":\"Unauthorized.\"}".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(response);
            return exchange.getResponse().writeWith(Flux.just(buffer));
        }
        return chain.filter(exchange.mutate().request(request).build());
    };
}

   @Override
   public Config newConfig() {
       return new Config("AuthorizationRequestFilter");
   }

   public static class Config {

    public Config(String name) {
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
   }

   @Override
   public int getOrder() {
       return 1;
   }
}

Is there any way I can achieve this in a single place where I can configure both?

Vijay
  • 558
  • 6
  • 22

0 Answers0