我前端使用的 Vue,向后端 Spring Boot 资源服务器发起请求。我在配置后端时遇到了问题。
在前端发起 GET 请求或在 Postman 中发起请求都没问题。但是其他方法的请求(例如 PUT)只能用 Postman 发送,如果前端发送的话会返回 401 错误。我怀疑是 CORS 跨域的问题,所以我禁用了 cors:
http
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((auth) -> auth
.requestMatchers(AntPathRequestMatcher.antMatcher("/h2-console/**")).permitAll()
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
但是,禁用了 CORS 后,前端发送 GET 请求也会失败。
@RestController
类中的 PUT 路由配如下:
@PutMapping("/test")
void test() {
System.out.println("called");
}
添加 @CrossOrigin
注解也不起作用。
GET 路由是这样的:
@GetMapping("/users")
List<RedditUser> all() {
return repo.findAll();
}
axios
的 PUT 请求如下:
async saveCurrentChanges() {
await axios.put("http://localhost:8080/api/test", { headers: { "Authorization": "Bearer " + getAuth().currentUser.accessToken }}).then((response) => {
console.log("success");
}).catch((error) => {
console.log(error);
});
},
我不理解的是,为啥 Postman 的请求可以,而前端的 PUT 请求却不行?
我启用了 Spring Security 日志后,请求失败可以看到如下输出:
2024-06-27T14:57:44.286+02:00 DEBUG 10700 --- [xp-backend] [nio-8080-exec-3] o.s.security.web.FilterChainProxy : Securing PUT /api/test
2024-06-27T14:57:44.286+02:00 DEBUG 10700 --- [xp-backend] [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
请求成功的日志如下(GET 请求):
2024-06-27T14:57:42.175+02:00 DEBUG 10700 --- [xp-backend] [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Securing GET /api/users
2024-06-27T14:57:42.460+02:00 DEBUG 10700 --- [xp-backend] [nio-8080-exec-2] o.s.s.o.s.r.a.JwtAuthenticationProvider : Authenticated token
2024-06-27T14:57:42.460+02:00 DEBUG 10700 --- [xp-backend] [nio-8080-exec-2] .s.r.w.a.BearerTokenAuthenticationFilter : Set SecurityContextHolder to JwtAuthenticationToken [Principal=org.springframework.security.oauth2.jwt.Jwt@abc94983, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[]]
2024-06-27T14:57:42.462+02:00 DEBUG 10700 --- [xp-backend] [nio-8080-exec-2] o.s.security.w