Spring Security 6 禁用各 Filter

Spring Security Spring Boot About 2,656 words

默认 Filter

Security filter chain: [
  DisableEncodeUrlFilter
  WebAsyncManagerIntegrationFilter
  SecurityContextHolderFilter
  HeaderWriterFilter
  CsrfFilter
  LogoutFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  ExceptionTranslationFilter
  AuthorizationFilter
]

禁用 DisableEncodeUrlFilter

禁止使用HttpSession

http.sessionManagement(AbstractHttpConfigurer::disable)

禁用 SecurityContextHolderFilter

禁止读取SessionrequestAttribute中的值

http.securityContext(AbstractHttpConfigurer::disable)

禁用 HeaderWriterFilter

会去掉X-Content-Type-OptionsX-XSS-ProtectionCache-ControlPragmaExpiresX-Frame-Options

http.headers(AbstractHttpConfigurer::disable)

禁用前

HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
vary: accept-encoding
Content-Encoding: gzip
Content-Type: text/html;charset=UTF-8
Content-Language: zh
Transfer-Encoding: chunked
Date: Fri, 10 Nov 2023 08:56:52 GMT
Keep-Alive: timeout=60
Connection: keep-alive

禁用后

HTTP/1.1 200
vary: accept-encoding
Content-Encoding: gzip
Content-Type: text/html;charset=UTF-8
Content-Language: zh
Transfer-Encoding: chunked
Date: Fri, 10 Nov 2023 08:57:56 GMT
Keep-Alive: timeout=60
Connection: keep-alive

禁用 CsrfFilter

禁用跨站请求伪造。

http.csrf(AbstractHttpConfigurer::disable)

禁用 LogoutFilter

禁用Spring Security自带的退出登录过滤器。

http.logout(AbstractHttpConfigurer::disable)

禁用 RequestCacheAwareFilter

禁用请求缓存(请求重放)。禁用保存在Session中的重定向地址等。

http.requestCache(AbstractHttpConfigurer::disable)

禁用 AnonymousAuthenticationFilter

禁用AnonymousAuthentication认证。

http.anonymous(AbstractHttpConfigurer::disable)

备注

BasicAuthenticationFilter以及UsernamePasswordAuthenticationFilterSpring Security 6中默认不注入。

完整禁用所有 Filter

@Bean
public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
    return http
            .securityMatcher("/api/**")
            .sessionManagement(AbstractHttpConfigurer::disable)
            .securityContext(AbstractHttpConfigurer::disable)
            .headers(AbstractHttpConfigurer::disable)
            .csrf(AbstractHttpConfigurer::disable)
            .logout(AbstractHttpConfigurer::disable)
            .requestCache(AbstractHttpConfigurer::disable)
            .anonymous(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests.anyRequest().permitAll())
            .build();
}

只有4个过滤器了

Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextHolderAwareRequestFilter
  ExceptionTranslationFilter
  AuthorizationFilter
]
Views: 1,019 · Posted: 2024-04-24

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh