可以通过获取 HttpSecurity 对象,然后调用它的 authorizeRequests() 方法,进而调用其 antMatchers() 方法,来获取放行的所有 URL 和 method。

示例代码:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/public/**").permitAll()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/")
                    .permitAll()
                    .and()
                .logout()
                    .logoutUrl("/logout")
                    .permitAll();
    }

    // ... 其他配置
}

在上面的代码中,我们定义了一个 HttpSecurity 配置,其中通过 antMatchers() 方法设置了一些放行的 URL 和 method,如 /public/**/admin/**,分别允许所有用户和拥有 ADMIN 角色的用户访问。我们可以在其他地方通过获取 HttpSecurity 对象,进而获取这些放行的 URL 和 method,示例代码如下:

@Autowired
private HttpSecurity httpSecurity;

private void printAntMatchers() {
    try {
        httpSecurity
                .getConfigurer(ChannelSecurityConfigurer.class)
                .getRegistry()
                .getMatchers().stream()
                .forEach(System.out::println);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

在上面的代码中,我们通过 @Autowired 注入了 HttpSecurity 对象,然后在 printAntMatchers() 方法中获取了 ChannelSecurityConfigurer 对象,进而通过 getMatchers() 方法获取了所有的放行的 URL 和 method,然后可以将其打印出来。

SpringBoot 获取 HttpSecurity 中配置的放行 URL 和 Method

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

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