一、问题
springboot 6.0版本,弃用.hasIpAddress()后,如何实现允许指定IP地址访问?
二、官方解释
旧版写法:
http
.authorizeRequests((authorize) -> authorize
.mvcMatchers("/app/**").hasIpAddress("127.0.0.1")
// ...
.anyRequest().denyAll()
)
// ...
新版写法:
首先定义IpAddressMatcher对象,然后access()方法来授权。
//127.0.0.1 可换成 其他需要放行的IP地址
IpAddressMatcher hasIpAddress = new IpAddressMatcher("127.0.0.1");
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/app/**").access((authentication, context) ->
new AuthorizationDecision(hasIpAddress.matches(context.getRequest()))
// ...
.anyRequest().denyAll()
)
// ...
三、在acwing springboot项目中的示例:
该示例为,acwing springboot项目在实现匹配微服务时,进行的SecurityConfig配置。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.IpAddressMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
IpAddressMatcher hasIpAddress = new IpAddressMatcher("127.0.0.1");
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/player/add/","/player/remove/").access((authentication, context) ->
new AuthorizationDecision(hasIpAddress.matches(context.getRequest())))
.requestMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated());
return http.build();
}
}