Tomcat 8 和 Spring Security Cors

我正在尝试配置 Spring Security 以使其支持 CORS。我已经使用 Spring Boot 使用以下配置代码使其在我的本地主机上工作:

@Configuration

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override

    protected void configure(HttpSecurity http) throws Exception {

        http.cors()

        .and()

        .antMatcher("/api/**")

        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

        .and()

        .authorizeRequests()

        .antMatchers(HttpMethod.POST, "/api/login").permitAll()

        .antMatchers(HttpMethod.GET, "/api/websocket/**").permitAll()

        .antMatchers("/api/**").authenticated()

        .and()

        .addFilterBefore(new JWTLoginFilter("/api/login", HttpMethod.POST, authenticationManager(), tokenAuthenticationService, myUserService), UsernamePasswordAuthenticationFilter.class)

        .addFilterBefore(new JWTAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class)

        .csrf().disable();

    }


@Bean

public CorsConfigurationSource corsConfigurationSource() {

    final CorsConfiguration configuration = new CorsConfiguration();

    configuration.setAllowedOrigins(ImmutableList.of("*"));

    configuration.setAllowedMethods(ImmutableList.of("HEAD",

            "GET", "POST", "PUT", "DELETE", "PATCH"));

    // setAllowCredentials(true) is important, otherwise:

    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

    configuration.setAllowCredentials(true);

    // setAllowedHeaders is important! Without it, OPTIONS preflight request

    // will fail with 403 Invalid CORS request

    configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

    source.registerCorsConfiguration("/**", configuration);

    return source;

}

}

这是失败的 OPTIONS 请求的屏幕截图:

https://img1.sycdn.imooc.com/65a790db0001f7fe08570640.jpg

以及我的本地主机上的工作请求:

https://img1.sycdn.imooc.com/65a790e90001827008600694.jpg



Cats萌萌
浏览 60回答 5
5回答

UYOU

Spring security 提供了一种在 http 配置器中配置 CORS 的方法,有一种更简洁的方法可以将 CORS 过滤器添加到应用程序中 -@Component @Order(Ordered.HIGHEST_PRECEDENCE)public class MyCORSFilterClass implements Filter {@Overridepublic void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) res;response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));response.setHeader("Access-Control-Allow-Credentials", "true");response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");chain.doFilter(req, res);}@Overridepublic void init(FilterConfig filterConfig) {}@Overridepublic void destroy() {}}以最高优先级对过滤器进行排序可确保 javax.servlet.Filter 的 MyCORSFilterClassimplementation 是链中的第一个。

江户川乱折腾

尝试在本地方法中放置一个调试点corsConfigurationSource()并检查它是否正在执行。如果它没有被执行,请调查原因 - 可能通过启用 Spring 的调试日志和/或重新检查 Spring 配置。另外,尝试添加选项setAllowedMethodsconfiguration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));

慕无忌1623718

响应403反映授权失败。您的服务器可能已设置为要求对选项请求进行授权。您必须确保选项配置为发送成功响应(2xx 状态代码),以允许浏览器发送实际请求。2xx 响应通知浏览器服务器处理 CORS 请求。您的请求在本地有效的原因可能是您在提出请求时已获得授权。因此,请检查您的身份验证以确保其正确。因此,飞行前请求不会发送任何授权标头,因此您不应该在服务器端进行期望。

叮当猫咪

检查 tomcat 服务器是否在 $CATALINA_BASE/conf/web.xml 中配置了冲突的 CORS 过滤器

萧十郎

Tomcat 也有自己的 cors 过滤器,如果您在 tomcat 之前使用其他服务器(例如 nodejs、apache 服务器 vs ),也请检查其 cors 过滤器。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java