为了账号安全,请及时绑定邮箱和手机立即绑定

Tomcat 8 和 Spring Security Cors

Tomcat 8 和 Spring Security Cors

Cats萌萌 2024-01-17 16:32:27
我正在尝试配置 Spring Security 以使其支持 CORS。我已经使用 Spring Boot 使用以下配置代码使其在我的本地主机上工作:@Configurationpublic 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();    }@Beanpublic 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 请求的屏幕截图:以及我的本地主机上的工作请求:
查看完整描述

5 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

Spring security 提供了一种在 http 配置器中配置 CORS 的方法,有一种更简洁的方法可以将 CORS 过滤器添加到应用程序中 -


@Component 

@Order(Ordered.HIGHEST_PRECEDENCE)

public class MyCORSFilterClass implements Filter {

@Override

public 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);

}

@Override

public void init(FilterConfig filterConfig) {

}


@Override

public void destroy() {

}

}

以最高优先级对过滤器进行排序可确保 javax.servlet.Filter 的 MyCORSFilterClassimplementation 是链中的第一个。


查看完整回答
反对 回复 2024-01-17
?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

  1. 尝试在本地方法中放置一个调试点corsConfigurationSource()并检查它是否正在执行。如果它没有被执行,请调查原因 - 可能通过启用 Spring 的调试日志和/或重新检查 Spring 配置。

  2. 另外,尝试添加选项setAllowedMethods

    configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));



查看完整回答
反对 回复 2024-01-17
?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

响应403反映授权失败。您的服务器可能已设置为要求对选项请求进行授权。您必须确保选项配置为发送成功响应(2xx 状态代码),以允许浏览器发送实际请求。2xx 响应通知浏览器服务器处理 CORS 请求。

您的请求在本地有效的原因可能是您在提出请求时已获得授权。因此,请检查您的身份验证以确保其正确。因此,飞行前请求不会发送任何授权标头,因此您不应该在服务器端进行期望。


查看完整回答
反对 回复 2024-01-17
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

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



查看完整回答
反对 回复 2024-01-17
?
萧十郎

TA贡献1815条经验 获得超12个赞

Tomcat 也有自己的 cors 过滤器,如果您在 tomcat 之前使用其他服务器(例如 nodejs、apache 服务器 vs ),也请检查其 cors 过滤器。



查看完整回答
反对 回复 2024-01-17
  • 5 回答
  • 0 关注
  • 53 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信