import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.IpAddressMatcher;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class IpAccessControlConfiguration {
@Bean
public IpAccessControlExtension ipAccessControlExtension() {
return new IpAccessControlExtension();
}
@Configuration
@Order(1)
public static class IpAccessControlConfig extends WebSecurityConfigurerAdapter {
private final IpAccessControlExtension ipAccessControlExtension;
public IpAccessControlConfig(IpAccessControlExtension ipAccessControlExtension) {
this.ipAccessControlExtension = ipAccessControlExtension;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 应用IP访问控制规则
http.authorizeRequests()
.anyRequest().access("@ipAccessControlExtension.hasIpAccess(request, authentication)");
}
}
public static class IpAccessControlExtension {
private Map<String, String> whiteList = new HashMap<>();
private Map<String, String> blackList = new HashMap<>();
public IpAccessControlExtension() {
// 初始化白名单和黑名单
whiteList.put("192.168.1.0/24", "白名单IP段");
blackList.put("10.0.0.0/8", "黑名单IP段");
}
public boolean hasIpAccess(Object request, Object authentication) {
String remoteAddr = ((javax.servlet.http.HttpServletRequest) request).getRemoteAddr();
IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(whiteList.keySet());
// 设置白名单规则
ipAddressMatcher.setNegated(false);
评论已关闭