Spring Security 返回 403 Forbidden

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

我尝试像这样在Java中定义我的SecurityFilterChain,对“/game/**”的GET请求,...没问题,但是当我尝试请求“/user/all”时,它返回403禁止。为什么它没有返回 401 未经授权而是返回 403?

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(a -> a
                    .requestMatchers("/game/**",  "/gametype/**", "/publisher/**", "/platform/**" )
                        .permitAll())
            .authorizeHttpRequests(a -> a.requestMatchers("/user/**")
                            .authenticated()
          )
            .authenticationProvider(authenticationProvider)
            .sessionManagement(a -> a
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            //                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
            .build();
}

我尝试传递基本身份验证用户名和密码,但它只返回 403 Forbidden,因此我无法执行更多操作。请帮我!第一次学习Java 编辑:我对登录流程有点困惑。我没有设置任何有关权限的内容,但它仍然返回 403,这意味着我没有权限访问它,一开始我以为我会返回 401 但不是:(

java spring-boot spring-security security-filter
1个回答
0
投票

不确定这是否有效,但你可以尝试下面的代码

@Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.csrf().disable()
                .authorizeHttpRequests((authorize) ->
                        //authorize.anyRequest().authenticated()
                        authorize.requestMatchers(HttpMethod.GET, "/api/**").permitAll()
                                .requestMatchers("/api/auth/**").permitAll()
                                .anyRequest().authenticated()

                );

        return http.build();
    }

参考:使用 Spring Boot、Spring Security、Hibernate 和 MySQL 数据库登录和注册 REST API

另外我认为你必须使用

and()
来组合匹配器。 请参阅:java - 如何使用 Spring Security 为特定端点添加 HTTP 基本身份验证? - 堆栈溢出

如果您通过 UI 登录,请尝试使用

loginProcessingUrl
。请参阅 Spring Security loginPage 与 loginProcessingURL 中的答案 - 代码日志

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