使用 Spring Boot 開發 API 使用 Spring Security + OAuth2 + JWT 鑒權,已經在 Controller 配置允許跨域:
@RestController
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class XXController {
}
但是前端反饋,登錄接口可以正常訪問,但是需要鑒權的接口報跨域錯誤:
Access to XMLHttpRequest at 'http://******' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
開始以為是前端寫法問題,后來排查很久發現是 Spring Security 的配置文件中漏掉了配置項: cors() 詳細代碼如下:
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/v2/api-docs").permitAll()
.anyRequest().authenticated()
.and().cors() // 需要添加此配置項
.and().csrf().disable();
}
因為自己的疏忽,浪費不少時間,特此記錄!
2019/07/15 更新
也可以使用全局配置,可以省略 @CrossOrigin 和 .and().cors() 配置:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//設置允許跨域的路徑
registry.addMapping("/**")
//設置允許跨域請求的域名
.allowedOrigins("*")
//這里:是否允許證書 不再默認開啟
.allowCredentials(true)
//設置允許的方法
.allowedMethods("*")
//跨域允許時間
.maxAge(3600);
}