Spring Security 配置多种拦截规则

Spring Security Spring Boot About 1,295 words

单一配置

Spring Security 6中如果没有指定securityMatcher,默认会拦截所有路径。

@Bean
SecurityFilterChain securityFilterChain1(HttpSecurity http) throws Exception {
    http
            .authorizeHttpRequests(authorizeHttpRequests ->
                    authorizeHttpRequests.anyRequest().authenticated()
            );
    return http.build();
}

多配置

Spring Security 6中使用securityMatcher,配置多种路径拦截规则。

如果配置的SecurityFilterChain都应用了securityMatcher,则不符合拦截规则的路径,都将不会被Spring Security拦截。

@Bean
@Order(0)
SecurityFilterChain securityFilterChain0(HttpSecurity http) throws Exception {
    http
            .securityMatcher("/web/**")
            .authorizeHttpRequests(authorizeHttpRequests -> {
                authorizeHttpRequests.requestMatchers("/web/login").permitAll();
                authorizeHttpRequests.anyRequest().authenticated();
            });
    return http.build();
}

@Bean
@Order(1)
SecurityFilterChain securityFilterChain1(HttpSecurity http) throws Exception {
    http
            .securityMatcher("/api/**")
            .authorizeHttpRequests(authorizeHttpRequests ->
                    authorizeHttpRequests.anyRequest().authenticated()
            );
    return http.build();
}

参考文档

https://docs.spring.io/spring-security/reference/6.1/servlet/configuration/java.html#_multiple_httpsecurity_instances

Views: 452 · Posted: 2024-04-26

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh