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

CORS不能用于与Spring Security结合的Spring Boot应用程序

杜楚
2023-03-14

我将Spring Security(4.2.2)添加到Spring Boot(1.5.3)项目中,并实现了一个运行良好的令牌身份验证。

然后我试着添加CORS。当我现在调用API时,preflightoptions请求返回400,但是下面的get请求返回401。如果我禁用Spring安全CORS工作正常。所以,我假设在过滤器排序方面有一些不理想的地方。

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private UserDetailsService apiUserDetailsService;

    @Autowired
    private SecurityService securityService;

    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .userDetailsService(this.apiUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
        return new AuthenticationTokenFilter();
    }

    @Bean
    public SecurityService securityService() {
        return this.securityService;
    }

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.debug(true);
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors();

        httpSecurity
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(this.unauthorizedHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/orchestrator/feedback/authenticate/**").permitAll()
                .requestMatchers(new RegexRequestMatcher("/orchestrator/feedback/\\w{2}/applications/\\d+/?", "GET", true)).permitAll()
                .requestMatchers(new RegexRequestMatcher("/orchestrator/feedback/\\w{2}/applications/?", "GET", true)).permitAll()
                .anyRequest().authenticated();

        httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    }
}
@Configuration  
public class WebConfig extends WebMvcConfigurerAdapter {

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

我已经尝试了自定义过滤器或FilterRegistrationBean,但没有任何帮助。是HttpSecurity构建器部分出了问题,还是我有另一个错误?

Spring Security日志:

2017-05-30 13:11:55.939  INFO 36146 --- [io-8081-exec-10] Spring Security Debugger                 : 

************************************************************

Request received for OPTIONS '/orchestrator/feedback/de/applications/1?_=1496142715197':

org.apache.catalina.connector.RequestFacade@4699afc5

servletPath:/orchestrator/feedback/de/applications/1
pathInfo:null
headers: 
host: localhost:8081
connection: keep-alive
pragma: no-cache
cache-control: no-cache
access-control-request-method: GET
origin: http://localhost
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
access-control-request-headers: content-type
accept: */*
referer: http://localhost/
accept-encoding: gzip, deflate, sdch, br
accept-language: en-GB,en;q=0.8,en-US;q=0.6,de;q=0.4,fr;q=0.2,it;q=0.2,es;q=0.2,pt;q=0.2


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CorsFilter
  LogoutFilter
  AuthenticationTokenFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************


2017-05-30 13:11:56.073  INFO 36146 --- [nio-8081-exec-1] Spring Security Debugger                 : 

************************************************************

Request received for GET '/orchestrator/feedback/de/applications/1?_=1496142715197':

org.apache.catalina.connector.RequestFacade@4699afc5

servletPath:/orchestrator/feedback/de/applications/1
pathInfo:null
headers: 
host: localhost:8081
connection: keep-alive
pragma: no-cache
cache-control: no-cache
accept: application/json, text/javascript, */*; q=0.01
origin: http://localhost
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
content-type: application/json; charset=utf-8;
referer: http://localhost/
accept-encoding: gzip, deflate, sdch, br
accept-language: en-GB,en;q=0.8,en-US;q=0.6,de;q=0.4,fr;q=0.2,it;q=0.2,es;q=0.2,pt;q=0.2


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CorsFilter
  LogoutFilter
  AuthenticationTokenFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************


2017-05-30 13:11:56.075  INFO 36146 --- [nio-8081-exec-1] Spring Security Debugger                 : 

************************************************************

Request received for GET '/error?_=1496142715197':

org.apache.catalina.core.ApplicationHttpRequest@7a954096

servletPath:/error
pathInfo:null
headers: 
host: localhost:8081
connection: keep-alive
pragma: no-cache
cache-control: no-cache
accept: application/json, text/javascript, */*; q=0.01
origin: http://localhost
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
content-type: application/json; charset=utf-8;
referer: http://localhost/
accept-encoding: gzip, deflate, sdch, br
accept-language: en-GB,en;q=0.8,en-US;q=0.6,de;q=0.4,fr;q=0.2,it;q=0.2,es;q=0.2,pt;q=0.2


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CorsFilter
  LogoutFilter
  AuthenticationTokenFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************


2017-05-30 13:11:56.075 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2017-05-30 13:11:56.076 DEBUG 36146 --- [nio-8081-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2017-05-30 13:11:56.076 DEBUG 36146 --- [nio-8081-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2017-05-30 13:11:56.076 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/error] is: -1
2017-05-30 13:11:56.076 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.cors.DefaultCorsProcessor        : Skip CORS processing: response already contains "Access-Control-Allow-Origin" header
2017-05-30 13:11:56.077 DEBUG 36146 --- [nio-8081-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Written [{timestamp=Tue May 30 13:11:56 CEST 2017, status=401, error=Unauthorized, message=Access Denied, path=/orchestrator/feedback/de/applications/1}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@32efecf2]
2017-05-30 13:11:56.077 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-05-30 13:11:56.078 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Successfully completed request

共有1个答案

印子平
2023-03-14

@crossorigin添加到控制器中,它将允许CORS

 类似资料:
  • 一个使用Jersey在Java中构建的方法,它接受两个参数并存储在数据库中,它可以和postman一起正常工作,但当我在Android应用程序中使用它时,它不起作用。我试图通过截击和改装发送请求。 服务器端代码: Android代码: 公共无效寄存器(最终字符串用户名、最终字符串密码){ 邮差回应 截击请求: 公共无效寄存器Volley(最终字符串用户名,最终字符串密码){

  • 当我不接触任何关于CORS的东西时,浏览器会向我显示常见错误 CORS策略阻止了从源http://localhost:3000获取http://localhost:8080/denodo-testwebapp/tags的访问 但与此同时,在邮递员上做一个GET请愿书,我用所有数据来回复 但当我试图通过添加以下代码禁用CORS时: 我不再有浏览器错误,但现在,在postman上做同样的GET请愿书,

  • 本文向大家介绍SpringBoot 配合 SpringSecurity 实现自动登录功能的代码,包括了SpringBoot 配合 SpringSecurity 实现自动登录功能的代码的使用技巧和注意事项,需要的朋友参考一下 自动登录是我们在软件开发时一个非常常见的功能,例如我们登录 QQ 邮箱: 很多网站我们在登录的时候都会看到类似的选项,毕竟总让用户输入用户名密码是一件很麻烦的事。 自动登录功能

  • 我对springfox和Swagger2都是新手。我一直在尝试将SpringFox/Swagger2与我的spring boot微服务集成以生成API文档。 我遵循了“http://springfox.github.io/springfox/docs/snapshot/”站点中给出的步骤。但是我没有成功的带来api文档页面。 每当我试图点击URL“http://localhost:8081/swa

  • 我希望文档的显示方式类似于它在特定于应用程序的上下文路径下的文档中提到的方式。你能告诉我我错过了什么吗?

  • 我正在设置Angular Spring Security模块来登录和注册用户。当我注册一个用户时,一切都正常。注册后的最后一步是自动登录,但我遇到了以下错误: XMLHttpRequest无法加载超文本传输协议//localhost:8080/com-tesis/login.请求的资源上不存在“访问控制允许起源”标头。因此不允许访问起源“超文本传输协议//localhost:9000”。响应的HT