代码之家  ›  专栏  ›  技术社区  ›  Meriç Bulca

Spring安全过滤器链请求匹配器工作不正常

  •  0
  • Meriç Bulca  · 技术社区  · 3 年前
    enter code here http
                .csrf(AbstractHttpConfigurer::disable)
                .cors(customizer -> customizer
                        .configurationSource(request -> {
                            CorsConfiguration config = new CorsConfiguration();
                            config.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
                            config.setAllowedMethods(Collections.singletonList("*"));
                            config.setAllowedHeaders(Collections.singletonList("*"));
                            config.setAllowCredentials(true);
                            config.setMaxAge(3600L);
                            return config;
                        }))
                .authorizeHttpRequests(customizer -> customizer
                        .requestMatchers("/api/v1/auth/**").permitAll()
                        .requestMatchers("/api/v1/auth/validate-session").authenticated()
                        .requestMatchers("/api/v1/demo").authenticated()
                        .anyRequest().authenticated()
                )
                .sessionManagement(customizer -> customizer
                        .invalidSessionUrl("/api/v1/auth/logout?expired")
                        .maximumSessions(1)
                        .maxSessionsPreventsLogin(false)
                )
                .httpBasic(Customizer.withDefaults())
                .logout(customizer -> customizer
                        .logoutUrl(LOGOUT_URL)
                        .logoutSuccessUrl(LOGOUT_SUCCESS_URL)
                        .invalidateHttpSession(true)
                        .deleteCookies("JSESSIONID")
                );
        return http.build();
    

    我无法保护/api/v1/auth/validate会话,因为我允许/api/v1/auth/**。我想在允许其他请求的同时,使安全的验证会话端点成为可能。是否有任何方法可以覆盖该模式。

    0 回复  |  直到 3 年前
        1
  •  1
  •   barkeldiho    3 年前

    正如Slevin在您原始帖子的评论中指出的那样,Spring Security规则是程序性应用的。这意味着对于每个请求,规则都是自上而下评估的。因此,您需要从最详细的规则开始,并推广到最后。例如。:

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(auth -> auth.requestMatchers(HttpMethod.GET, this.partiallyPublic).permitAll())
                .authorizeHttpRequests(auth -> auth.requestMatchers(this.completelyPublic).permitAll())
                .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                ....
    
        return http.addFilterAfter(new RequestLoggingFilter(), BearerTokenAuthenticationFilter.class).build();
    }
    

    在这个例子中,我使用this.partiallyPublic配置了第一个URL,该URL在HEAD、OPTIONS、GET类型的Http请求方面应该是公共的。之后,我授予访问此完全公共资源的权限。所有其他请求都需要经过身份验证