SpringBoot整合SpringSecurity以后如何解决跨域问题

什么是跨域问题.
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript 施加的安全限制。

什么是同源
所谓同源是指 域名、协议、端口均相同

  • http://www.abc.com --> http://test.abc.com 跨域
  • http://www.abc.com --> http://www.abc.com 非跨域
  • http://www.abc.com --> http://www.abc.com:8080 跨域
  • https://www.abc.com --> http://www.abc.com 跨域
  • localhost 和 127.0.0.1 虽然都指向本机,但也属于跨域

接下主要讲解使用 CORS 解决跨域问题,其他解决方法本文不在阐述!

使用 CROS(跨域资源共享)解决跨域问题

CORS 是一个 W3C 标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出 XMLHttpRequest 请求,从而克服了 AJAX 只能同源使用的限制。

添加GlobalCorsConfig配置文件来允许跨域访问

@Configuration
public class
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合JWT时,处理跨域问题可以采用以下几种方法: 1. 使用CORS(跨源资源共享)配置:在Spring Boot中,可以通过添加CORS配置来允许特定的源访问API。可以在`WebMvcConfigurer`配置类中添加`addCorsMappings`方法来实现。例如,允许所有源访问API可以使用以下配置: ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("*") .allowedHeaders("*") .allowCredentials(true); } } ``` 2. 使用Spring Security配置:如果你使用了Spring Security来保护API,并且已经配置了JWT认证,可以在`WebSecurityConfigurerAdapter`配置类中添加跨域配置。例如: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() // 其他配置... } } ``` 3. 使用过滤器处理跨域请求:可以创建一个自定义的过滤器来处理跨域请求。该过滤器可以在请求到达控制器之前添加跨域相关的响应头。例如: ```java @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Headers", "authorization, content-type"); response.setHeader("Access-Control-Max-Age", "3600"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } // 其他方法... } ``` 这些方法可以根据你的具体需求选择使用。通过配置CORS或Spring Security,或使用自定义过滤器,可以解决Spring Boot整合JWT时的跨域问题

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值