当前位置: 首页 > 知识库问答 >
问题:

Spring boot中的Cors策略问题:自定义头问题

商宏爽
2023-03-14

我们正在开发一个Spring Boot程序和angularjs应用程序。我们使用JWT令牌和LDAP身份验证。LDAP身份验证后,service生成jwt令牌并发送给angular,从下一次开始,angular将令牌和用户名发送回service,angular将令牌存储在会话存储中。

setHeaders: {
    "customHeader1":"userName",
    "customHeader2":"jwtToken"
 }
@Configuration
 public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/*").permitAll();
        http.cors();
    }

   @Bean
   public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    List<String> originList = new ArrayList<String>();
    List<String> methodList = new ArrayList<String>();
    List<String> headerList = new ArrayList<String>();
    originList.add("*"); 
    methodList.add("HEAD");methodList.add("GET");methodList.add("POST");methodList.add("PUT");
    methodList.add("DELETE");methodList.add("PATCH");
    headerList.add("Authorization");
    headerList.add("Cache-Control");
    headerList.add("Content-Type");
    headerList.add("customHeader1");
    headerList.add("customHeader2");
    configuration.setAllowedOrigins(Collections.unmodifiableList(originList)); 
    configuration.setAllowedMethods(Collections.unmodifiableList(methodList));
    // 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(Collections.unmodifiableList(headerList));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
   }
@Component
public class CustomAuthInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String header1 = null;
    String header2 = null;

        if (StringUtils.isNotBlank(request.getHeader("customHeader1"))) {
            header1 = request.getHeader("customHeader1");
        }
        if (StringUtils.isNotBlank(request.getHeader("customHeader2"))) {
            header2 = request.getHeader("customHeader2");
        }
        System.out.println("customtoken="+header1+"|customUserName="+header2); 

            //LDAP service call


                if (StringUtils.equalsIgnoreCase(response, "success")) {
                    return true;
                } else {
                    response.setStatus(<CUSTOM_ERROR_CODE>); //custom error code
                    return false;
                }
          } 
      }
   }
@Configuration
public class CustomWebConfig implements WebMvcConfigurer
{
   @Autowired
   private CustomAuthInterceptor customAuthInterceptor ;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(customAuthInterceptor);
    }

   @Override
   public void addCorsMappings(CorsRegistry registry) {
       registry.addMapping("/**")
       .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
  }

有人能解决这个问题吗????

共有1个答案

壤驷麒
2023-03-14

飞行前请求被阻止,因为您没有启用选项请求类型。

将此语句添加到Cors Bean配置中。

methodList.add("OPTIONS");
 类似资料:
  • 我试图生成一个简单的axios请求,如下所示(我正在使用vue.js): 但我得到以下错误: 我已经尝试过添加下面的头,但仍然不起作用 但是如果我尝试通过浏览器发出请求(简单地通过复制和粘贴url),一切都很好。 有人知道怎么帮我吗?非常感谢!

  • 在构建自定义身份验证策略时,我使用钩子在需要时创建我的用户。 一切都很顺利,包括我的钩子: 然后我用它来消耗 但我有以下错误 代码:0错误名称:“未记录错误”消息:“无法使用策略”SSO“登录” 知道我为什么会有这样的问题吗? 问候

  • 我正在尝试使用自定义标题访问登录API。首先我得到了CORS错误: CORS策略阻止从http://localhost:3000的URL访问XMLHttpRequest:对预飞行请求的响应不通过权限改造检查:请求的资源上不存在访问控制允许起源头 然后我通过没有CORS插件禁用了CORS。现在我得到: 从“源”访问“URL”处的XMLHttpRequesthttp://localhost:3000'

  • 我正在尝试使用Java读取excel(.xls和.xlsx)。我能正确地阅读xlsx。但当我使用以下代码读取xls文件时 我犯错了 java.lang.nosuchmethoderror:org.apache.poi.hssf.usermodel.hssfrow.getcell(ilorg/apache/poi/ss/usermodel/row$missingcellpolicy;)log/apa

  • 我正在尝试创建一个反应应用程序,我需要从 url“https://news.google.com/news/rss”解析一些 RSS 新闻提要,但我收到错误“请求已被 CORS 策略阻止:”请求的资源上不存在'访问控制-允许来源'标头”。我在 Android 应用程序中做了类似的项目,我在 java 中使用 AsyncTasks 获取了一些提要,它没有向我显示任何 CORS 问题,我想了解为什么它

  • 我使用camel框架处理jetty组件。 我有两个问题: 1)我使用大消息(约1mb)和jetty组件将消息正文读取到骆驼交换标头中。它会导致这样的错误: 所以,我如何才能使jetty组件不将HttpRequest主体放入标头中? 2) 当我试图重写默认的HeaderFilterStrategy时,我编写了这样一段代码: 它引起了这样的例外: 原因:组织。阿帕奇。骆驼ResolveEndpoint