Allow OPTIONS HTTP Method for oauth/token request

前端 未结 5 1385
不思量自难忘°
不思量自难忘° 2020-12-04 19:17

I\'m trying to enable oauth2 token fetching for my angular application. My configuration is working fine (authentication is working correctly for all requests, token fetchin

5条回答
  •  难免孤独
    2020-12-04 19:59

    Same problem with Spring-Boot 1.4.7.RELEASE

    My WebSecurityConfigurerAdapter was using SecurityProperties.ACCESS_OVERRIDE_ORDER so, selected answer did not work.

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    public class AuthServerSecurityConfig extends WebSecurityConfigurerAdapter 
    

    Thus, I added the following filter configuration with preceding order:

      @Bean
      public FilterRegistrationBean corsFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(corsConfigurationSource()));
        bean.setOrder(SecurityProperties.DEFAULT_FILTER_ORDER);
        return bean;
      }
    
      @Bean
      public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return source;
      }
    

    and it got the job done.

    Note: equivalent result can be achieved with a javax.servlet.Filter bean with @Order(SecurityProperties.DEFAULT_FILTER_ORDER) annotation as below:

    @Component
    @Order(SecurityProperties.DEFAULT_FILTER_ORDER)
    public class CorsFilter implements Filter {
    
      @Override
      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
    
        response.setHeader("Access-Control-Allow-Origin"  , "*"                               );
        response.setHeader("Access-Control-Allow-Methods" , "POST, PUT, GET, OPTIONS, DELETE" );
        response.setHeader("Access-Control-Allow-Headers" , "Authorization, Content-Type"     );
        response.setHeader("Access-Control-Max-Age"       , "3600"                            );
    
        if("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
          response.setStatus(HttpServletResponse.SC_OK);
        }
        else {
          chain.doFilter(req, res);
        }
      }
      // ...
    }
    

提交回复
热议问题