Spring Security与Vue开发时,如果只是vue设置代理,会报CORS错误。需要前端和后台一起设置
1、前端
设置代理
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
host: 'localhost',
port: 8081,
proxy: {
'/' : {
target: 'http://localhost:8080',
changeOrigin: true,
ws: false
}
}
}
})
如果涉及到session需要添加
axios.defaults.withCredentials=true
2、后台
Spring Security设置支持跨域访问
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(corsConfigurationSource()).and().csrf().
disable().addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
}
CorsConfigurationSource corsConfigurationSource() {
// 提供CorsConfiguration实例,并配置跨域信息
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
corsConfiguration.setAllowedMethods(Arrays.asList("*"));
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:8081"));
corsConfiguration.setAllowCredentials(true);//涉及到session时添加
corsConfiguration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}