Skip to content

Instantly share code, notes, and snippets.

@Gsealy
Last active December 27, 2019 07:10
Show Gist options
  • Save Gsealy/da3ec35eaf8a00f39a6d698a443390c0 to your computer and use it in GitHub Desktop.
Save Gsealy/da3ec35eaf8a00f39a6d698a443390c0 to your computer and use it in GitHub Desktop.
BlockedBlackListGatewayFilterFactory
import com.alibaba.fastjson.JSON;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/**
* <pre>
* {@code
* // example code
* FilterDefinition filterDefinition = new FilterDefinition();
* Map<String, String> filterParams = Maps.newHashMap();
* List<String> strings = Lists.newArrayList("127.0.0.1", "localhost");
* filterDefinition.setName("BlockedBlackList");
* filterParams.put("blockip", JSON.toJSONString(strings));
* filterDefinition.setArgs(filterParams);
* }
* </pre>
*
* @author Gsealy
* @date 2018-10-25 14:10:36
*/
@Slf4j
@Component
public class BlockedBlackListGatewayFilterFactory extends
AbstractGatewayFilterFactory<BlockedBlackListGatewayFilterFactory.Config> {
public static final String BLOCK_IP_KEY = "blockip";
public BlockedBlackListGatewayFilterFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(BLOCK_IP_KEY);
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
if (config.getBlockIPList().contains(ip)) {
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
return exchange.getResponse().setComplete();
} else {
return chain.filter(exchange);
}
};
}
@Override
public String name() {
return "BlockedBlackList";
}
public static class Config {
public String BlockIP;
public List<String> BlockIPList;
public void setBlockIP(String blockIP) {
BlockIP = blockIP;
}
public List<String> getBlockIPList() {
BlockIPList = (List<String>) JSON.parseObject(BlockIP, List.class);
return BlockIPList;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment