點擊上方的語言選單以切換語言
適用技術棧:Spring Boot + Spring Security + JWT + Vue3
使用情境:前後端分離、本地開發(localhost 不同 port)
請求格式錯誤,後端無法解析。
一句話:你送的資料不對。
驗證失敗,伺服器不知道你是誰。
已通過驗證,但沒有權限存取。
一句話:我知道你是誰,但你不能。
伺服器內部錯誤。
如果你改了很多 auth / jwt / service 類別都沒效果,代表請求在 Spring Security Filter 就被擋掉了。
Authorization: Bearer <jwt-token>
請在 Chrome F12 → Network → Request Headers 確認。
前端:http://localhost:5173
後端:http://localhost:8080
→ 不同 origin,必須設定 CORS
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("http://localhost:5173"));
config.setAllowedMethods(List.of("GET","POST","PUT","DELETE","OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
瀏覽器會先送 OPTIONS,如果沒放行就直接 403。
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
JWT + 前後端分離,通常必須關 CSRF。
csrf(csrf -> csrf.disable())
axios.post('/api/login', data, {
headers: {
'Content-Type': 'application/json'
}
})
| 錯誤現象 | 首要懷疑對象 |
|---|---|
| Console 報 403,但後端 Log 沒動靜 | CORS 設定 或 Spring Security Filter |
後端 Log 報 Bad Credentials |
JWT SecretKey 錯位 或 過期 |
| 後端 Log 有進 Controller 但噴 400 | Jackson 解析 DTO 失敗 (欄位名稱對不上) |