@SpringBootApplicationpublicclassAuthorityManagementApplicationextendsWebSecurityConfigurerAdapter {publicstaticvoidmain(String[] args) {
SpringApplication.run(AuthorityManagementApplication.class, args);
}
@Overrideprotectedvoidconfigure(HttpSecurity http) throws Exception {
/**
* CORS 必须在Security之前处理
* 原因:这个 pre-flight 请求不会包含任何cookies,如果请求不包括任何cookies和Security先处理的话,那么这个请求会被拒绝
* 官方地址:https://docs.spring.io/spring-security/site/docs/5.0.0.RELEASE/reference/htmlsingle/#cors
* CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the JSESSIONID).
* If the request does not contain any cookies and Spring Security is first,
* the request will determine the user is not authenticated (since there are no cookies in the request) and reject it.
*/
http.cors();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:63342"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE"));
// 如果所有的属性不全部配置,一定要执行该方法
configuration.applyPermitDefaultValues();
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}