跨域
前端和后端的跨域問題,主要是由于瀏覽器同源策略
的限制,同源
一般指相互請求資源的兩個域的協議、域名(主域名以及子域名)和端口號都相同,其中任何一個不相同就會出現跨域請求被限制的問題。
同源策略的限制主要是為了避免瀏覽器受到 XSS、CSFR 等的攻擊;同源策略限制的內容有 Cookie、LocalStorage、IndexdDB 等存儲數據;Dom節點;AJAX 請求被攔截;但是 img 標簽的 src 屬性、a 標簽的 href 屬性以及 script 中的 src 屬性是可以跨域加載資源的
跨域并不是請求發不出去,后端是可以收到前端請求并且正常的返回結果的,只是結果被瀏覽器給攔截了。
CORS
CORS
(Cross-Origin Resource Sharing)是一種跨域資源共享技術標準,是目前解決前端跨域請求的主流方案,它支持多種 HTTP 請求方法(JSONP 只支持 GET 請求)。根據請求方法的不同,在處理上也有所不同:
簡單請求
:瀏覽器直接發送請求,并在請求頭中增加一個Origin
字段指定頁面的域,如果服務端支持該跨域請求則會在響應頭返回Access-Control-Allow-Origin
字段來告訴瀏覽器哪些域可以請求該資源,后邊瀏覽器會根據該字段的值決定是否限制跨域請求,滿足以下條件屬于簡單請求:
- 請求方式只能是:GET、POST、HEAD
- HTTP請求頭限制這幾種字段:Accept、Accept-Language、Content-Language、Content-Type、Last-Event-ID
- Content-type只能取:application/x-www-form-urlencoded、multipart/form-data、text/plain
復雜請求
:請求方法是 PUT、DELETE,或者 Content-Type 類型是 application/json 的請求就是復雜請求,這些跨域請求會在正式發送前先發送一次OPTIONS
類型的預檢請求,預檢請求頭Origin
用來指定發送請求的瀏覽器頁面的域、Access-Control-Request-Method
用來指定跨域請求類型;服務端如果允許該跨域請求則會在響應頭返回對應的字段Access-Control-Allow-Origin
、Access-Control-Allow-Method
(允許跨域的請求類型)、Access-Control-Max-Age
(預檢請求的有效期,單位秒),預檢請求完成后的就會發送真正的請求,步驟和簡單請求基本一致
下邊介紹的具體解決方案也是基于 CORS 的后端解決方案。
@CrossOrigin
@CrossOrigin(origins = "*")
@RestController
public class HelloController {
// @CrossOrigin(origins = "*")
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
@CrossOrigin
注解可以用在控制器類上,此時該控制器中的所有接口都支持跨域;也可以用在指定接口上,讓這個接口支持跨域訪問。可以看到@CrossOrigin
需要配置在每個控制器類中,屬于局部配置,無法做到一次性配置,會有些重復工作,后邊介紹的方案則不會有這樣的問題。
@CrossOrigin
注解可以配置以下屬性:
-
origins
:允許的域,* 表示所有,一般可以指定具體的域, -
allowedHeaders
:允許的請求頭字段,* 表示所有 -
exposedHeaders
:哪些響應頭可以作為響應的一部分暴露出來 -
methods
:允許的請求方法(GET、POST...),* 表示所有 -
allowCredentials
:是否允許瀏覽器發送憑證信息,例如 Cookie -
maxAge
: 預檢請求的有效期,有效期內不用再發出預檢請求
addCorsMappings
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 可以被跨域請求的接口,/**此時表示所有
.allowedMethods("*")
.allowedOrigins("*")
.allowedHeaders("*")
.allowCredentials(false)
.exposedHeaders("")
.maxAge(3600);
}
}
這種方式和@CrossOrigin
方式要配置的屬性基本一樣,大致原理也類似,都是在DispatcherServlet
中觸發跨域處理,配置了一個CorsConfiguration
對象,然后用該對象創建CorsInterceptor
攔截器,然后在攔截器中調用DefaultCorsProcessor#processRequest
方法,完成對跨域請求的校驗。
CorsFilter
@Configuration
public class CorsFilterConfig {
@Bean
FilterRegistrationBean<CorsFilter> corsFilter() {
FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
CorsFilter filter = new CorsFilter(source);
registrationBean.setFilter(filter);
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registrationBean;
}
}
這里使用的是跨域過濾器,在過濾器的doFilterInternal
方法中調用 DefaultCorsProcessor#processRequest
方法,完成對跨域請求的校驗;核心的配置和前邊兩種方案類似,這里由CorsConfiguration
來完成,由于過濾器的執行時機早于攔截器,所以CorsFilter
處理跨域的時機早于@CrossOrigin
、addCorsMappings
。
Spring Security
項目中如果使用了 Spring Security,則會導致前邊介紹的跨域解決方案失效,因為 Spring Security 是基于過濾器的實現的(最終是FilterChainProxy
),過濾器會先于攔截器執行,導致復雜請求的預檢請求(OPTIONS
)被 Spring Security 攔截,所以@CrossOrigin
、addCorsMappings
會可能失效,有一種方案是放行預檢請求,但是放行請求并不安全,所以使用了 Spring Security 后不建議再使用@CrossOrigin
、addCorsMappings
方案。
同樣的原理,如果CorsFilter
設置的優先級低于 FilterChainProxy
(默認-100) 則CorsFilter
方案也會失效,可以提高CorsFilter
的優先級(例如 Ordered.HIGHEST_PRECEDENCE),這樣使用 Spring Security 就不會有影響了。
其實在 Spring Security 中已經提供了更加優雅的跨域解決方案,不用考慮前邊的問題,配置類如下:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("zhangsan").password("{noop}123456").roles("admin").build());
auth.userDetailsService(manager);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// .antMatchers(HttpMethod.OPTIONS).permitAll() // 放行 @CrossOrigin、addCorsMappings 的預檢請求
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.formLogin()
// .loginPage("/login")
.loginProcessingUrl("/doLogin")
.successHandler((httpServletRequest, httpServletResponse, authentication) -> {
User user = (User) authentication.getPrincipal();
writeMessage(httpServletResponse, new ObjectMapper().writeValueAsString(user));
System.out.println("login success");
})
.failureHandler((httpServletRequest, httpServletResponse, e) -> {
System.out.println("login failure");
})
.permitAll()
.and()
.logout()
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> {
System.out.println("logout success");
})
.permitAll()
.and()
.exceptionHandling()
.authenticationEntryPoint((request, response, authException) -> {
response.setStatus(401);
writeMessage(response, "please login");
System.out.println("please login");
})
.and().cors().configurationSource(corsConfigurationSource()) // Spring Security 的跨域配置
.and()
.csrf().disable();
}
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
private void writeMessage(HttpServletResponse response, String message) throws IOException {
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(message);
out.flush();
out.close();
}
}
內容看著很多,其實和跨域相關的配置只有.and().cors().configurationSource(corsConfigurationSource())
,其中corsConfigurationSource()
方法的配置和CorsFilter
方案中的類似。
源碼地址:https://github.com/shehuan/cors
本文完!