解决403 Forbidden问题

爱被打了一巴掌 2024-02-19 08:11 202阅读 0赞

目录

  • 解决403 Forbidden问题
    • 场景
    • 原因
    • 解决

解决403 Forbidden问题

场景

一般403出现在前端跨域调用后端接口的情况下。

如vue前端通过http的方式请求后端接口时:

浏览器状态码:Status Code: 403。

此时控制台错误信息为:Access to XMLHttpRequest at ‘http://localhost:8048/tools/auth/login’ from origin ‘http://localhost:8888’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: ‘No Access-Control-Allow-Origin’header is present on the requested resource.

403前端报错信息

原因

前端URL: http://localhost:8888/
后端URL: http://localhost:8048/tools/auth/login

请求url中协议http、域名localhost、端口8048,前后端之间三者有任意一者不同时,即为跨域!!!

可见,该例子中端口不同,存在跨域问题。

解决

前后端跨域问题可以通过在后端添加CorsFilter来处理CORS问题。
代码如下:

  1. package com.anban.internaltools.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.cors.CorsConfiguration;
  5. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  6. import org.springframework.web.filter.CorsFilter;
  7. /**
  8. * @Author:
  9. * @Date: 2023/8/15 14:50
  10. * @Description: 添加描述
  11. */
  12. @Configuration
  13. public class MyCorsConfig {
  14. @Bean
  15. public CorsFilter corsFilter() {
  16. CorsConfiguration configuration = new CorsConfiguration();
  17. // configuration.addAllowedOrigin("http://localhost:8888");// 允许谁跨域
  18. configuration.addAllowedOrigin("*");// 允许所有人跨域
  19. configuration.setAllowCredentials(true);// 传cookie
  20. configuration.addAllowedMethod("*");// 允许哪些方法跨域 post get
  21. configuration.addAllowedHeader("*");// 允许哪些头信息
  22. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  23. source.registerCorsConfiguration("/**", configuration);// 拦截一切请求
  24. return new CorsFilter(source);
  25. }
  26. }

若后端设置为:

  1. configuration.addAllowedOrigin("http://localhost:8888");// 允许谁跨域

此时需要留意前端服务,从本地调试完毕部署服务器时,一定要留意前后端服务部署ip和端口是否符合配置,否则容易出现,vue前端项目部署成功后,无法访问后端,一直报错403 Forbidden。

若出现以上问题,将后端配置更改为:

  1. configuration.addAllowedOrigin("*");// 允许所有人跨域

如果不想放开所有地址的跨域访问,也支持多名单设置:

  1. configuration.addAllowedOrigin("http://localhost:8888");// 允许谁跨域
  2. configuration.addAllowedOrigin("http://192.168.7.9:80");
  3. configuration.addAllowedOrigin("http://15.173.5.188.:8080");

发表评论

表情:
评论列表 (有 0 条评论,202人围观)

还没有评论,来说两句吧...

相关阅读

    相关 nginx 403 Forbidden

    问题在于,我们使用weblogic在前台系统获取其他系统的文件,然后保存在webloigc目录下,然后配置了nginx来当http服务器,这样,其他的系统可以来下载文件,但是访

    相关 nginx 403 Forbidden

      nginx服务配置完成后,访问出现403 Forbidden ![20181231140608455.JPG][] 通过分析403错误和其它测试方式测,可以确认,是访