Spring Boot 中使用 Spring Security, OAuth2 跨域問題 (自己挖的坑)


使用 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);
    }

參考:Spring-boot2.0 前后端分離項目 跨域問題


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM