spring-boot跨域问题

本文介绍了如何在SpringMVC中自定义CORSConfig类以处理跨域请求,并指出SpringSecurity中formLogin模式下,使用axios进行非表单提交时可能出现的问题及其解决方案。

1. 自定义CORSConfig类

该类实现WebMvcConfigurer接口,重写addCorsMappings方法	
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CORSConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}

2. 需要注意,SpringSecurityConfig类中处理登录过程中,要启用cors

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 登录过程的处理
        http.csrf(csrf -> csrf.disable())
                .addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin(loginForm -> loginForm
                        .loginProcessingUrl("/user/login")
                        .successHandler(loginSuccessHandler)
                        .failureHandler(loginFailureHandler)
                        .usernameParameter("username")
                        .passwordParameter("password"))
                .sessionManagement(sessMgr -> sessMgr.sessionCreationPolicy((SessionCreationPolicy.STATELESS))) // 不创建session
                .authenticationProvider(authenticationProvider())
                .authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests
                        .requestMatchers(HttpMethod.OPTIONS).permitAll() // 设置需要拦截的请求
                        .requestMatchers("/user/login").permitAll() // 登录请求放行(不拦截)
                        .anyRequest().authenticated())// 其它一律请求都需要进行身份认证
                .exceptionHandling(exceptionHandling -> exceptionHandling
                        .authenticationEntryPoint(anonymousAuthentticationHandler) // 匿名无权限访问
                        .accessDeniedHandler(customerAccessDeniedHandler)) // 认证用户无权限访问
                .cors(); // 支持跨域请求

        return http.build();
    }

特别重要的一点

如果你的security的config里面设置了.formLogin(),那么前台提交就必须要用form表单提交,若使用的axios,需要模拟form提交。原本是表单提交的,后来因为测试改成用Axios提交,结果搞了好久没搞定,找了一下资料才发现是这个问题。

axios.post(url, params, {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    })
### Spring Boot Starter Web Services与Spring Boot Starter Web的区别 #### 功能定位差异 `spring-boot-starter-web-services` 主要用于构建基于SOAP协议的Web服务应用,专注于提供支持JAX-WS标准的服务端实现[^1]。而 `spring-boot-starter-web` 则更侧重于RESTful风格的应用开发,它集成了Spring MVC框架来简化HTTP请求处理逻辑。 #### 技术栈区别 对于想要创建传统的面向服务架构(SOA)中的Web Service来说,会选择使用 `spring-boot-starter-web-services` ,因为其内部包含了必要的库文件如CXF或Spring WS等,这些工具能够帮助开发者快速搭建起符合WSDL描述的服务接口。 相反地,当目标是建立现代轻量级API网关或是微服务之间的通信机制时,则更适合采用 `spring-boot-starter-web` 。该模块默认配置了一个嵌入式的Servlet容器(比如Tomcat),并提供了丰富的特性集合,包括但不限于JSON序列化/反序列化、异常映射以及资源共享(CORS)[^2]。 #### 使用场景举例 假设有一个项目需求是要对接银行系统的转账功能,通常这类金融服务会遵循严格的行业标准,因此可能需要用到 `spring-boot-starter-web-services` 来确保兼容性和安全性;而对于一个社交平台上的点赞评论等功能,则完全可以利用 `spring-boot-starter-web` 提供的强大路由管理和数据绑定能力来进行高效开发[^3]。 ```xml <!-- Example of using spring-boot-starter-web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Example of using spring-boot-starter-web-services --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web-services</artifactId> </dependency> ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值