import org.springframework.context.annotation.configuration;
import org.springframework.http.server.reactive.serverhttprequest;
import org.springframework.stereotype.component;
import org.springframework.web.reactive.config.corsregistry;
import org.springframework.web.reactive.config.webfluxconfigurer;
import org.springframework.web.server.serverwebexchange;
import org.springframework.web.server.webfilter;
import org.springframework.web.server.webfilterchain;
import reactor.core.publisher.mono;
import java.net.inetsocketaddress;
import java.util.objects;
/*
if you want to keep spring boot webflux features and you want to add additional webflux configuration, you can add your own @configuration class of type webfluxconfigurer but without @enablewebflux.
if you want to take complete control of spring webflux, you can add your own @configuration annotated with @enablewebflux.
*/
@configuration
public class webconfiguration implements webfluxconfigurer {
@override
public void addcorsmappings(corsregistry registry) {
registry
.addmapping("/**")
.allowedorigins("*")
.allowedmethods("get", "post", "put", "patch", "delete", "option")
.allowedheaders("header1", "header2", "header3")
.exposedheaders("header1", "header2")
.allowcredentials(true)
.maxage(3600);
}
/**
* https://stackoverflow.com/questions/51192630/how-do-you-get-clients-ip-address-spring-webflux-websocket?rq=1
* https://stackoverflow.com/questions/50981136/how-to-get-client-ip-in-webflux
* https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-filters
* 由于在低版本的 spring-webflux 中不支持直接获得请求 ip(https://jira.spring.io/browse/spr-16681),因此写了一个补丁曲线救国,
* 从 org.springframework.web.server.serverwebexchange 中获得 ip 后,在放到 header 里
*/
@component
public static class retrieveclientipwebfilter implements webfilter {
@override
public mono<void> filter(serverwebexchange exchange, webfilterchain chain) {
inetsocketaddress remoteaddress = exchange.getrequest().getremoteaddress();
string clientip = objects.requirenonnull(remoteaddress).getaddress().gethostaddress();
serverhttprequest mutatedserverhttprequest = exchange.getrequest().mutate().header("x-client-ip", clientip).build();
serverwebexchange mutatedserverwebexchange = exchange.mutate().request(mutatedserverhttprequest).build();
return chain.filter(mutatedserverwebexchange);
}
}
}