WebSecurityConfigurerAdapter 不存在
时间: 2024-10-12 11:04:07 浏览: 12
对不起,关于`WebSecurityConfigurerAdapter`的问题可能是基于旧版本的Spring Security描述。实际上,在Spring Security 5及以后的版本中,`WebSecurityConfigurerAdapter`已被标记为过时,并引入了更现代和声明式的`WebFluxSecurityBuilder`或`WebSecurity`接口来配置安全设置。
如果你是在Spring Security 5.x或更新的版本中工作,你可以按照以下步骤配置:
1. **引入依赖**:
确保添加Spring Security Web相关的依赖,比如 `spring-boot-starter-security-oauth2-client` 或者其他所需的模块。
2. **配置WebSecurity**:
替换`WebSecurityConfigurerAdapter`,使用`WebSecurity`接口,例如:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig {
@Bean
public HttpSecurity http() {
return HttpSecurity.withauthorizeRequests()
.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.permitAll();
}
}
```
3. **启动WebSecurity**:
在`Application`类中,调用`configure`方法启动WebSecurity配置:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@SpringBootApplication
@EnableWebSecurity
public class MyApplication {
private final SecurityConfig config;
@Autowired
public MyApplication(SecurityConfig config) {
this.config = config;
}
public static void main(String[] args) {
new SpringApplicationBuilder(MyApplication.class).run(args);
}
@Bean
public FilterRegistrationBean<?> securityFilterChain() {
return new FilterRegistrationBean<>(config.http());
}
}
```
请注意,以上代码示例适用于基于HTTP的请求,如果是WebFlux架构,你需要调整为使用`WebFluxSecurity`。
阅读全文