.requestMatchers("/").permitAll() 不起作用

问题描述 投票:0回答:1

以下代码中连接到“localhost:8080”或“localhost:8080/”时出现403错误。

它适用于其他 URL。

仅根 URL 不起作用。

我以为我可以访问 localhost:8080 无需身份验证。


@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authprovider = new DaoAuthenticationProvider();
        authprovider.setUserDetailsService(userService.userDetailsService());
        authprovider.setPasswordEncoder(passwordEncoder);
        return authprovider;
    }

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/").permitAll()
                        .anyRequest().authenticated()
                )
                .authenticationProvider(authenticationProvider())
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}
java spring authentication security
1个回答
0
投票

403 错误通常意味着服务器理解该请求,但拒绝授权。在 Spring Security 的上下文中,似乎配置可能导致了问题。

您当前的配置允许对“/”的所有请求,但后续的“.anyRequest().authenticated()”行需要对任何其他请求进行身份验证。然而,由于“/”请求被第一条规则捕获,因此它永远不会到达第二条规则。

要解决此问题,您可以:

通过修改配置以允许“.anyRequest().authenticated()”行之前的所有请求来显式允许访问所有请求。

配置安全过滤器以不同方式处理“/”。例如,您可以允许所有对“/”的请求,然后对其他端点应用身份验证。

以下是调整配置的方法:

java

复制代码

http
    .csrf(csrf -> csrf.disable())
    .sessionManagement(session -> session
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    )
    .authorizeHttpRequests(authorize -> authorize
        .antMatchers("/").permitAll()  // Allow access to root URL
        .anyRequest().authenticated()   // Require authentication for other requests
    )
    .authenticationProvider(authenticationProvider())
    .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

此调整明确允许访问根 URL(“/”),并要求对任何其他请求进行身份验证。这应该可以解决请求“localhost:8080”或“localhost:8080/”的 403 错误。

© www.soinside.com 2019 - 2024. All rights reserved.