springboot+vue项目中,加上这个跨域请求拦截就会无法登录,应该怎么解决


关注引自免费微信小程序:皆我百晓生
针对你描述的问题,Spring Boot + Vue 项目在添加了跨域请求拦截配置后无法登录的情况,我们可以从几个角度来分析并解决这个问题。
首先,检查你的跨域配置代码中有一些小错误,例如 addALLowedOrigin 应为 allowedOrigin,但实际的正确写法是 allowOrigins。此外,registerCorsConfiguration 方法的参数中的 path 是一个错误的键名,正确的应该是使用 UrlPathHelper 的默认路径匹配器,无需额外指定路径键。以下是修正后的代码示例:
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:80");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
但是,这里有一个更简洁的写法,使用 Spring Boot 的自动配置特性,可以将上述代码简化为:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("http://localhost:80");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
接下来,确保你的前端 Vue 应用正在向正确的后端 URL 发送请求。在开发环境中,Vue 通常运行在 http://localhost:8080 或其他端口上,而你的跨域配置中只允许了 http://localhost:80 的请求。因此,你需要确认前端发送请求的 URL 是否与你配置的允许访问的 URL 匹配。
最后,检查你的 Spring Security 配置是否可能阻止了登录请求。如果你有安全相关的配置,例如 CSRF 保护或其他身份验证过滤器,它们可能会干扰到跨域请求的处理。确保你的安全配置允许预检请求(OPTIONS 方法),并正确处理 CORS 凭证。
如果以上步骤都无法解决问题,建议检查服务器的日志输出,以获取更多关于 403 错误的具体原因的信息。这将有助于进一步定位问题所在。