springboot 403

作者: 垃圾简书_吃枣药丸 | 来源:发表于2018-11-07 11:59 被阅读2次

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

# 1.项目未添加Security依赖

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

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


    OPTIONS请求
  • 控制台:


    console

    出现了跨域情况

# 解决方案 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

    OK了

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


    原请求

# 解决方案 2

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

# 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请求到达服务器后是谁做出的响应

相关文章

  • springboot 403

    跨域资源共享 CORS 详解 - 阮一峰 # 1.项目未添加Security依赖 前端地址: http://loc...

  • setUnauthorizedUrl("/403&qu

    SpringBoot中集成Shiro的时候, 配置setUnauthorizedUrl("/403")了,但是不起...

  • Spring boot全局异常处理405,415,500

    首先把SpringBoot默认的异常处理屏蔽掉: 如下代码, 其中401,403处理是配合shiro使用的, 当没...

  • SpringBoot 项目访问接口报401、403

    1). 场景 添加 Redis 之后,出现 Security 相关类找不到的问题 2). 解决 引入 Spring...

  • 403

    市场的问题在最近几个月一个苦扰着许多品牌,我们也不例外。在过去的几个月里,每个同事都花很多时间在自己的工作上,想让...

  • To 403

    鉴于我没有沈佳琳那么多废话,我就写个全部人的(毕竟这么好的渠道我也要好好利用) 既然如此,我们就按年龄吧!哈哈哈(...

  • 403

    放不下,怎么放得下。403

  • 403

  • 403

    一直对烹饪没啥兴趣,间断的玩过甜点之类的玩意儿,基本热情不会超过2周,就搁置了。今天和娃儿单挑,又突然有了兴趣给娃...

  • 403

    8.21 天气:雨 我喜欢立秋后的雨天,清冷。开着风扇会起鸡皮,却也不愿穿上外套隔绝了这冷意,只好关掉。 今天有...

网友评论

    本文标题:springboot 403

    本文链接:https://www.haomeiwen.com/subject/kbwmxqtx.html