SpringSecurity 不使用 WebSecurityConfigurerAdapter
时间: 2024-02-28 14:45:50 浏览: 17
如果不使用WebSecurityConfigurerAdapter,可以通过注册一个WebSecurityCustomizer bean来配置Spring Security。在这个bean中,可以使用web.ignoring()方法来忽略一些URL路径,例如"/ignore1"和"/ignore2"。这样就可以实现不使用WebSecurityConfigurerAdapter的配置了。
相关问题
在springboot配置springsecurity 可以使用 WebSecurityConfigurerAdapter
来实现。
1.创建一个类并继承WebSecurityConfigurerAdapter
2.覆盖configure(HttpSecurity http)方法来配置安全策略
3.覆盖configure(AuthenticationManagerBuilder auth)方法来配置用户认证信息
示例代码:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
这个示例代码配置了一个简单的安全策略,允许所有用户访问主页和登录页面,但是需要认证才能访问其他页面。认证信息是在内存中配置的,用户名为"user",密码为"password",角色为"USER"。在实际使用中,需要根据实际情况配置更加复杂的安全策略和用户认证信息。
SpringSecurityConfig extends WebSecurityConfigurerAdapter
根据提供的引用内容,可以得知SpringSecurityConfig是一个类,它继承了WebSecurityConfigurerAdapter类。因此,可以在SpringSecurityConfig类中覆盖WebSecurityConfigurerAdapter类的方法,以实现对WebSecurity的定制配置。
以下是一个示例代码:
```java
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
.antMatchers("/").permitAll()
.and().formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
在上面的示例代码中,我们覆盖了WebSecurityConfigurerAdapter类的configure(HttpSecurity http)方法和configure(AuthenticationManagerBuilder auth)方法,以实现对HttpSecurity和AuthenticationManagerBuilder的定制配置。同时,我们还提供了一个PasswordEncoder的Bean,用于加密用户密码。