使用 Spring Boot 开发 API 使用 Spring Security + OAuth2 + JWT 鉴权,已经在 Controller 配置允许跨域:
1 | @RestController |
但是前端反馈,登录接口可以正常访问,但是需要鉴权的接口报跨域错误:
1 | 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() 详细代码如下:
1 | @Override |
因为自己的疏忽,浪费不少时间,特此记录!
2019/07/15 更新
也可以使用全局配置,可以省略 @CrossOrigin 和 .and().cors() 配置:
1 | @Configuration |