在Spring Security 5中,WebSecurityConfigurerAdapter已被弃用,建议使用更加灵活的方式进行配置。因此,如果您正在使用Spring Boot 2.x或更高版本,建议使用以下方式配置:

1.创建一个类,继承WebSecurityConfigurer,并实现configure(HttpSecurity http)方法。

2.在configure(HttpSecurity http)方法中,使用HttpSecurity对象配置您的安全性需求。例如,您可以定义哪些URL需要被保护,哪些角色可以访问它们等等。

3.在您的配置类上使用@EnableWebSecurity注解,以启用Spring Security。

下面是一个简单的示例:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/public/**").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")
                .and()
                .withUser("admin").password("{noop}password").roles("USER", "ADMIN");
    }

}

在这个示例中,我们定义了一个名为SecurityConfig的配置类,它扩展了WebSecurityConfigurerAdapter。我们还使用@EnableWebSecurity注解启用了Spring Security。

在configure(HttpSecurity http)方法中,我们使用HttpSecurity对象定义了我们的安全性需求。我们定义了哪些URL需要被保护,哪些角色可以访问它们等等。我们还定义了登录页面和注销URL。

在configureGlobal(AuthenticationManagerBuilder auth)方法中,我们定义了两个用户,一个是普通用户,一个是管理员用户。这些用户将被存储在内存中,以便进行身份验证。

最后,我们需要注意的是,我们不再需要在应用程序的配置文件中手动定义Spring Security的默认用户名和密码。在这个示例中,我们使用了一个简单的明文密码,但在实际应用中,您应该使用更安全的密码存储方式,例如BCryptPasswordEncoder。

Consider defining a bean of type orgspringframeworksecurityconfigannotationwebbuildersHttpSecurity in your configuration使用springboot304的错误解决方法不能使用弃用的WebSecurityConfigurerAdapter

原文地址: https://www.cveoy.top/t/topic/bqgu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录