springboot 403

简介: springboot 403

跨域资源共享 CORS 详解 - 阮一峰


# 1.项目未添加Security依赖



前端地址: http://localhost:9528

后端地址: http://localhost:8889


  • 前端调用接口 localhost:8888/user/login
  • 对于非简单请求,浏览器首先会发起一个OPTIONS预检请求,询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些HTTP动词和头信息字段。只有得到肯定答复,浏览器才会发出正式的XMLHttpRequest请求,否则就报错。

image.png

image.png


控制台:


image.png

  • 出现了跨域情况


# 解决方案 1


在filter中添加白名单,完整filter代码⤵️

package com.futao.springmvcdemo.foundation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
/**
 * @author futao
 * Created on 2018/9/19-15:47.
 */
@WebFilter(filterName = "AppFilter", urlPatterns = "/*")
public class AppFilter implements Filter {
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ArrayList<String> allowOrigins = (ArrayList<String>) req.getServletContext().getAttribute("allowOrigins");
        String origin = request.getHeader("Origin");
        if (allowOrigins.contains(origin)) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        }
        // Access-Control-Max-Age
        response.setHeader("Access-Control-Max-Age", "3600");
        // Access-Control-Allow-Credentials
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // Access-Control-Allow-Methods
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        chain.doFilter(req, resp);
    }
    @Override
    public void init(FilterConfig config) throws ServletException {
        //白名单
        ArrayList<String> allowOrigins = new ArrayList<>();
        allowOrigins.add("http://localhost:63343");
        allowOrigins.add("http://localhost:9528");
        config.getServletContext().setAttribute("allowOrigins", allowOrigins);
    }
}


  • 再次发起请求


image.png

image.png

  • OK了
  • 随后浏览器会自动发起原请求


image.png

image.png

# 解决方案 2


  • 新建CorsConfiguration配置类,自己百度


# 3


@SpringBootConfiguration
public class WebMvcConfiguration implements WebMvcConfigurer 
@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedMethods("*")
                .allowedHeaders("Content-Type")
                .allowedOrigins(SystemConfiguration.ALLOWORIGINS)
                .maxAge(SystemConfiguration.ORIGINMAXAGE);
    }

# 2.项目添加了Security依赖


需要额外添加如下配置

package com.futao.springmvcdemo.foundation;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
 * @author futao
 * Created on 2018/11/6.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers(HttpMethod.OPTIONS, "/**");
    }
}


如果同时进行了filter和CorsConfiguration的配置,OPTIONS请求会返回403,并且控制台提示It does not have HTTP ok status.,非常恶心。

疑问:OPTIONS请求到达服务器后是谁做出的响应

相关文章
|
Java
http访问springboot接口出现401 、403、 Forbidden 错误解决方法
http访问springboot接口出现401 、403、 Forbidden 错误解决方法
4170 0
|
对象存储
关于uniapp解决单/多文件上传的解决思路
关于uniapp解决单/多文件上传的解决思路
1311 0
|
并行计算 算法 搜索推荐
简单学习一下AES算法:GCM、ECB、CFB、OFB等
简单学习一下AES算法:GCM、ECB、CFB、OFB等
3944 0
|
安全 Java 数据库
Spring Security 实战指南:从入门到精通
本文详细介绍了Spring Security在Java Web项目中的应用,涵盖登录、权限控制与安全防护等功能。通过Filter Chain过滤器链实现请求拦截与认证授权,核心组件包括AuthenticationProvider和UserDetailsService,负责用户信息加载与密码验证。文章还解析了项目结构,如SecurityConfig配置类、User实体类及自定义登录逻辑,并探讨了Method-Level Security、CSRF防护、Remember-Me等进阶功能。最后总结了Spring Security的核心机制与常见配置,帮助开发者构建健壮的安全系统。
2870 0
|
Linux 开发工具 git
【Git】Git 完全指南:从入门到精通
Git 是一种强大的版本控制工具,掌握了其基本命令和高级特性后,可以大大提高开发效率并方便团队协作。通过本篇文章,你已经学会了 Git 的核心命令及其使用方法,希望你能够灵活运用 Git 在实际项目中进行版本管理。
6004 4
|
Ubuntu Linux
Linux系统管理:服务器时间与网络时间同步技巧。
以上就是在Linux服务器上设置时间同步的方式。然而,要正确运用这些知识,需要理解其背后的工作原理:服务器根据网络中的其他机器的时间进行校对,逐步地精确自己的系统时间,就像一只犹豫不决的啮齿动物,通过观察其他啮齿动物的行为,逐渐确定自己的行为逻辑,既简单,又有趣。最后希望这个过程既能给你带来乐趣,也能提高你作为系统管理员的专业素养。
2639 20
|
开发框架 中间件 Java
如何处理跨域资源共享(CORS)的 OPTIONS 请求?
处理 CORS 的 OPTIONS 请求的关键是正确设置响应头,以告知浏览器是否允许跨域请求以及允许的具体条件。根据所使用的服务器端技术和框架,可以选择相应的方法来实现对 OPTIONS 请求的处理,从而确保跨域资源共享的正常进行。
1099 61
Redisson 分布式锁的正确使用
你会正确使用分布式锁吗?
3051 0
Redisson 分布式锁的正确使用
|
SQL 安全 数据可视化
代码审计神器:Fortify SCA 保姆级教程
代码审计神器:Fortify SCA 保姆级教程
代码审计神器:Fortify SCA 保姆级教程