栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

CORS问题

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

CORS问题

CORS的预检请求使用

OPTIONS
不带凭据的HTTP ,请参阅跨域资源共享:

否则,请发出预检请求。使用方法OPTIONS和以下附加约束,使用引荐来源来源作为覆盖引荐来源,并设置了手动重定向标志和块cookie标志,从起源来源起点获取请求URL:

  • 包括一个Access-Control-Request-Method标头,并将请求方法作为标头字段值(即使是简单方法也是如此)。
  • 如果作者请求标头不为空,则包含一个Access-Control-Request-Headers标头,并以字母顺序将按字母顺序排列的作者请求标头中的标头字段名的列表以逗号分隔,作为标头字段值,每个都转换为ASCII小写(即使是更多是一个简单的标题)。
  • 排除作者请求标头。
  • 排除用户凭据。
  • 排除请求实体主体。

你必须允许HTTP匿名访问OPTIONS。

你修改(简化)的代码:

@Overrideprotected void configure(HttpSecurity http) throws Exception {   http       .authorizeRequests().andMatchers(HttpMethod.OPTIONS, "/**").permitAll().antMatchers("/login").permitAll().anyRequest().fullyAuthenticated().and()       .httpBasic().and()       .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()       .csrf().disable();}

从Spring Security 4.2.0开始,你可以使用内置支持,请参阅Spring Security Reference:

  1. CORS

Spring framework为CORS提供了一流的支持。必须在Spring Security之前处理CORS,因为飞行前请求将不包含任何cookie(即

JSESSIONID
)。如果请求不包含任何cookie,并且首先使用Spring Security,则该请求将确定用户未通过身份验证(因为请求中没有cookie),并拒绝该用户。

确保首先处理CORS的最简单方法是使用

CorsFilter
。用户可以
CorsFilter
通过
CorsConfigurationSource
使用以下命令将集成到Spring Security中:

@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {  @Override  protected void configure(HttpSecurity http) throws Exception {      http          // by default uses a Bean by the name of corsConfigurationSource          .cors().and()          ...  }  @Bean  CorsConfigurationSource corsConfigurationSource() {      CorsConfiguration configuration = new CorsConfiguration();      configuration.setAllowedOrigins(Arrays.asList("https://example.com"));      configuration.setAllowedMethods(Arrays.asList("GET","POST"));      UrlbasedCorsConfigurationSource source = new UrlbasedCorsConfigurationSource();      source.registerCorsConfiguration("/**", configuration);      return source;  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383709.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号