如何修复Spring authorizeRequests被弃用?

k10s72fa  于 2022-12-02  发布在  Spring
关注(0)|答案(1)|浏览(2236)

Spring更新了,authorizeRequests被废弃了,antMatchers被删除了。有人能展示一下SpringSecurity应该是什么样子的吗?

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = false, securedEnabled = true)
public class SecurityConfig {

    private final PersonDetailsService personDetailsService;

    @Autowired
    public SecurityConfig(PersonDetailsService personDetailsService) {
        this.personDetailsService = personDetailsService;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/, /login, /signup, /logout").permitAll()
                .requestMatchers("/api").hasRole("ADMIN")
                .requestMatchers("/user").hasRole("USER")
                .anyRequest().authenticated())
                .logout().logoutUrl("/logout").logoutSuccessUrl("/").and()
                .formLogin().loginPage("/login").loginProcessingUrl("/login").defaultSuccessUrl("/user").failureUrl("/login?error");
        return http.build();
    }
}

阅读文档、堆栈溢出等没有找到解决方案。

5ktev3wc

5ktev3wc1#

您可以使用authorizeHttpRequests代替authorizeRequests,也可以使用requestMatchers代替antMatchers
例如:

http.authorizeHttpRequests()
  .requestMatchers("/authentication/**").permitAll()
  .requestMatchers("/h2/**").permitAll()
  .anyRequest().authenticated();

相关问题