为什么我的Spring安全配置也在permitAll端点上抛出403

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

我正在尝试使用 Spring security 建立一个新项目。该项目的目的是创建一些用于 React 界面的 Web API。目前,我使用的是 Spring boot 3.2.2 和 Spring security 6.2.1

我已经把大部分东西都设置好了。然而,由于某些原因,框架总是在我的 PermitAll() 端点上抛出 403。

下面是我的安全链对象:

 @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
    System.out.println(httpSecurity);
      return httpSecurity
                .authorizeHttpRequests((auth) -> auth
                        .requestMatchers("/api/myproject/admin/**") // I have tried removing this condition also
                        .hasRole("ADMIN")
                        .requestMatchers(HttpMethod.POST, "/public/login") // I have tried without context path also
                        .permitAll()
                        .requestMatchers(HttpMethod.POST, "/api/myproject/public/login") // tried with context path also
                        .permitAll()
                        .anyRequest().authenticated()
                    )
                .csrf(AbstractHttpConfigurer::disable) // tried disabling csrf as well
                .authenticationProvider(authenticationProvider())
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
                .build();

}

我已经浏览了很多类似的问题和文章,并尝试了很多东西,包括:

  1. 同时使用 GET 和 POST 作为我的登录端点(理想情况下我想要一个 POST)。
  2. 尝试禁用csrf
  3. 尝试放置带有和不带有上下文路径的端点路径(/api/myproject 是我的上下文路径)
  4. 尝试指定 HTTP POST 动词,如上所示
  5. 还尝试了上面的配置,删除了所有内容,只有 1 条登录路由规则

到目前为止,这些都对我不起作用。但是,如果允许的话一切都像:

return httpSecurity
            .authorizeHttpRequests((auth) -> auth
            .anyRequest().permitAll()

然后它对我有用,并使所有端点公开,包括登录端点。

我不确定我只将登录端点列入白名单作为公共端点做错了什么。有人可以帮忙吗?

编辑:添加下面的控制器代码:

@Slf4j
@RestController
@RequestMapping("/public")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> generateUserToken(@RequestBody LoginRequest loginRequest) {
        log.info("generateUserToken Started");
        String token = loginService.login(loginRequest.getEmailId(), loginRequest.getPwd());
        return ResponseEntity.ok(new LoginResponse(token));
    }

}

API 调用的邮递员 cUrl 是:

curl --location 'http://localhost:8080/api/myproject/public/login' \
--header 'Content-Type: application/json' \
--header 'Cookie: JSESSIONID=9E2DD3E4A04619324786B0F595BD96FD' \
--data-raw '{
    "emailId": "[email protected]",
    "pwd": "jhdsjhdj"
}'

谢谢

spring spring-boot authentication spring-mvc spring-security
1个回答
0
投票

您的 cURL 命令是 GET 而不是 POST。您必须提供带有

-X POST

的动词

在邮递员中,您放置了正文,但没有在动词的下拉列表中设置 POST。是的,当你放置身体时,它不会自动切换,这很奇怪。

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