本文介绍了弹簧安全CORS过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我们向我们现有的项目添加了 Spring Security 。 从这一刻起,我们得到一个401 否Access-Control-Allow-Origin头部存在于请求的资源错误从我们的服务器。 这是因为没有 Access-Control-Allow-Origin 标头附加到响应。为了解决这个问题,我们添加了我们自己的过滤器,它在注销过滤器之前的 Filter 链中,但过滤器不适用于我们的请求。 我们的错误:我们的安全配置: @EnableWebSecurity @Configuration @ComponentScan(com.company.praktikant) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private MyFilter filter; @Override public void configure(HttpSecurity http)throws Exception { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin(*); config.addAllowedHeader(*); config.addAllowedMethod(GET); config.addAllowedMethod(PUT); config.addAllowedMethod(POST); source.registerCorsConfiguration(/ **,config); http.addFilterBefore(new MyFilter(),LogoutFilter.class).authorizeRequests() .antMatchers(HttpMethod.OPTIONS,/ *)。 } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception {} } 我们的过滤器 @Component public class MyFilter extends OncePerRequestFilter { @Override public void destroy(){ } private String getAllowedDomainsRegex b $ b returnindividual / customized Regex; } @Override protected void doFilterInternal(HttpServletRequest请求,HttpServletResponse响应,FilterChain filterChain) throws ServletException,IOException { final String origin =http:// localhost:3000; response.addHeader(Access-Control-Allow-Origin,origin); response.setHeader(Access-Control-Allow-Methods,POST,GET,OPTIONS); response.setHeader(Access-Control-Allow-Credentials,true); response.setHeader(Access-Control-Allow-Headers,content-type,x-gwt-module-base,x-gwt-permutation,clientid,longpush filterChain.doFilter(request,response); } } 我们的申请 @SpringBootApplication public class Application { public static void main(String [] args){ final ApplicationContext ctx = SpringApplication.run(Application.class,args); final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(CORSConfig.class); annotationConfigApplicationContext.refresh(); } } 我们的过滤器是从spring-boot注册的: p> 我们生成的filterchain: 2016-11-04 09:19:52.729 INFO 9704 --- [ost-startStop-1] ossweb.DefaultSecurityFilterChain:创建过滤器链:org.springframework.security.web.util.matcher .AnyRequestMatcher @ 1,[org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@5d8c5a8a,org.springframework.security.web.context.SecurityContextPersistenceFilter@7d6938f,org.springframework.security.web.header.HeaderWriterFilter @ 72aa89c,org.springframework.security.web.csrf.CsrfFilter@4af4df11,com.company.praktikant.MyFilter@5ba65db2,org.springframework.security.web.authentication.logout.LogoutFilter@2330834f,org.springframework.security.web。 savedrequest.RequestCacheAwareFilter@396532d1,org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4fc0f1a2,org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2357120f,org.springframework.security.web.session.SessionManagementFilter@10867bfb,org。 springframework.security.web.access.ExceptionTranslationFilter@4b8bf1fb,org.springframework.security.web.access.intercept.FilterSecurityInterceptor@42063cf1] 回应: 回应标题 我们试着从春天的解决方案,但它没有工作!在控制器中的注释@CrossOrigin也没有帮助。 编辑1: @PiotrSołtysiak。 cors过滤器没有列在生成的过滤器链中,我们仍然得到相同的错误。我们使用的是spring-security版本4.1.3。解决方案好的,经过2天的搜索,我们终于解决了这个问题。我们删除了所有的过滤器和配置,而是在应用程序类中使用了这5行代码。 @SpringBootApplication public class Application { public static void main(String [] args){ final ApplicationContext ctx = SpringApplication.run(Application.class,args); } @Bean public WebMvcConfigurer corsConfigurer(){ return new WebMvcConfigurerAdapter(){ @Override public void addCorsMappings(CorsRegistry注册表){ registry.addMapping(/ **).allowedOrigins(http:// localhost:3000); } }; } } We added Spring Security to our existing project.From this moment on we get a 401 No 'Access-Control-Allow-Origin' header is present on the requested resource error from the our server.That's because no Access-Control-Allow-Origin header is attached to the response. To fix this we added our own filter which is in the Filter chain before the logout filter, but the filter does not apply for our requests.Our Error:Our Security configuration:@EnableWebSecurity@Configuration@ComponentScan("com.company.praktikant")public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Autowiredprivate MyFilter filter;@Overridepublic void configure(HttpSecurity http) throws Exception { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); source.registerCorsConfiguration("/**", config); http.addFilterBefore(new MyFilter(), LogoutFilter.class).authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/*").permitAll();}@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {}}Our filter@Componentpublic class MyFilter extends OncePerRequestFilter {@Overridepublic void destroy() {}private String getAllowedDomainsRegex() { return "individual / customized Regex";}@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { final String origin = "http://localhost:3000"; response.addHeader("Access-Control-Allow-Origin", origin); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "content-type, x-gwt-module-base, x-gwt-permutation, clientid, longpush"); filterChain.doFilter(request, response);}}Our Application@SpringBootApplicationpublic class Application {public static void main(String[] args) { final ApplicationContext ctx = SpringApplication.run(Application.class, args); final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(CORSConfig.class); annotationConfigApplicationContext.refresh();}}Our filter is registered from spring-boot:Our generated filterchain:The Response:Response headersWe tried the solution from spring as well but it didn't work! The annotation @CrossOrigin in our controller didn't help either.Edit 1:Tried the solution from @Piotr Sołtysiak.The cors filter isn't listed in the generated filter chain and we still get the same error.Btw we are using spring-security version 4.1.3.! 解决方案 Ok, after over 2 days of searching we finally fixed the problem. We deleted all our filter and configurations and instead used this 5 lines of code in the application class.@SpringBootApplicationpublic class Application {public static void main(String[] args) { final ApplicationContext ctx = SpringApplication.run(Application.class, args);}@Beanpublic WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("http://localhost:3000"); } };}} 这篇关于弹簧安全CORS过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-12 17:36