spring-boot跨域问题

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",
      },
    })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值