我正在尝试使用 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();
}
我已经浏览了很多类似的问题和文章,并尝试了很多东西,包括:
到目前为止,这些都对我不起作用。但是,如果允许的话一切都像:
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"
}'
谢谢
您的 cURL 命令是 GET 而不是 POST。您必须提供带有
-X POST
的动词
在邮递员中,您放置了正文,但没有在动词的下拉列表中设置 POST。是的,当你放置身体时,它不会自动切换,这很奇怪。