13

Tôi đang cố gắng thiết lập máy chủ Spring của mình với Spring Security 3.2 để có thể thực hiện yêu cầu đăng nhập ajax.Cách thiết lập bộ lọc Access-Control-Allow-Origin có vấn đề trong Spring Security 3.2

Tôi làm theo các Spring Security 3.2 video và vài bài viết nhưng vấn đề là tôi nhận được

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:9000' is therefore not allowed access. 

Đối với các yêu cầu đăng nhập (xem dưới đây).

Tôi đã tạo thiết lập CORSFilter và tôi có thể truy cập các tài nguyên không được bảo vệ trong hệ thống của mình với các tiêu đề thích hợp được thêm vào phản hồi.

Tôi đoán là tôi không thêm CORSFilter vào chuỗi bộ lọc bảo mật hoặc chuỗi có thể quá muộn trong chuỗi. Bất kỳ ý tưởng sẽ được đánh giá cao.

WebAppInitializer

public class WebAppInitializer implements WebApplicationInitializer { 
    @Override 
    public void onStartup(ServletContext servletContext) { 
     WebApplicationContext rootContext = createRootContext(servletContext); 

     configureSpringMvc(servletContext, rootContext); 

     FilterRegistration.Dynamic corsFilter = servletContext.addFilter("corsFilter", CORSFilter.class); 
     corsFilter.addMappingForUrlPatterns(null, false, "/*"); 
    } 

    private WebApplicationContext createRootContext(ServletContext servletContext) { 
     AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); 

     rootContext.register(SecurityConfig.class, PersistenceConfig.class, CoreConfig.class); 

     servletContext.addListener(new ContextLoaderListener(rootContext)); 
     servletContext.setInitParameter("defaultHtmlEscape", "true"); 

     return rootContext; 
    } 


    private void configureSpringMvc(ServletContext servletContext, WebApplicationContext rootContext) { 
     AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext(); 
     mvcContext.register(MVCConfig.class); 

     mvcContext.setParent(rootContext); 
     ServletRegistration.Dynamic appServlet = servletContext.addServlet(
       "webservice", new DispatcherServlet(mvcContext)); 
     appServlet.setLoadOnStartup(1); 
     Set<String> mappingConflicts = appServlet.addMapping("/api/*"); 

     if (!mappingConflicts.isEmpty()) { 
      for (String s : mappingConflicts) { 
       LOG.error("Mapping conflict: " + s); 
      } 
      throw new IllegalStateException(
        "'webservice' cannot be mapped to '/'"); 
     } 
    } 

SecurityWebAppInitializer:

public class SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer { 
} 

SecurityConfig:

Các yêu cầu để /api/người dùng - hoạt động tốt và các tiêu đề Access-Control-Allow được thêm vào. tôi CSRF tàn tật và các tiêu đề chỉ để chắc chắn đây không phải là trường hợp

@EnableWebMvcSecurity 
@Configuration 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
    protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication() 
       .withUser("user").password("password").roles("USER"); 
    } 


    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .csrf().disable() 
      .headers().disable()     
      .authorizeRequests() 
        .antMatchers("/api/users/**").permitAll() 
        .anyRequest().authenticated() 
        .and() 
      .formLogin() 
       .loginPage("/login") 
       .permitAll() 
       .and() 
      .logout() 
       .permitAll(); 
    } 

CORFilter:

@Component 
public class CORSFilter implements Filter{ 
    static Logger logger = LoggerFactory.getLogger(CORSFilter.class); 

    @Override 
    public void init(FilterConfig filterConfig) throws ServletException { 
    } 

    @Override 
    public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
     HttpServletResponse response = (HttpServletResponse) res; 
     response.setHeader("Access-Control-Allow-Origin", "*"); 
     response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 
     response.setHeader("Access-Control-Max-Age", "3600"); 
     response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 
     chain.doFilter(request, response); 
    } 

    public void destroy() {} 
} 

Login Yêu cầu:

Request URL:http://localhost:8080/devstage-1.0/login 
Request Headers CAUTION: Provisional headers are shown. 
Accept:application/json, text/plain, */* 
Cache-Control:no-cache 
Content-Type:application/x-www-form-urlencoded 
Origin:http://127.0.0.1:9000 
Pragma:no-cache 
Referer:http://127.0.0.1:9000/ 
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36 
Form Dataview sourceview URL encoded 
username:user 
password:password 
+0

Bạn có thể thêm cấu hình bảo mật Spring của mình không? –

Trả lời

17

Tất cả tôi đã mất tích được AddFilterBefore khi định cấu hình cấu hình bảo mật.

Vì vậy, phiên bản cuối cùng là:

@EnableWebMvcSecurity 
@Configuration 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception { 
    auth.inMemoryAuthentication() 
     .withUser("user").password("password").roles("USER"); 
    } 


    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class) 

      .formLogin() 
       .loginPage("/login") 
       .and() 
      .authorizeRequests() 
       .anyRequest().authenticated(); 

Và loại bỏ các CORSFilter từ WebAppInitializer

+0

Điều này dường như không hoạt động với Spring 4.2: ( – froginvasion

+0

không hoạt động cho tôi với Spring boot 1.4.0 – WhiteWater

0

Tôi biết đó là một chút quá muộn để trả lời câu hỏi của bạn, nhưng nghĩ có thể có giá trị để chia sẻ. Trong cấu hình ban đầu của bạn, bạn đã đăng ký siêu dữ liệu cấu hình khởi tạo Xuân An với bối cảnh gốc:

rootContext.register(SecurityConfig.class, PersistenceConfig.class, CoreConfig.class); 

Khi bạn có thể làm điều này, bạn không cần phải vì nó sẽ vài chuỗi bộ lọc bảo mật với bối cảnh ứng dụng web không bắt buộc. Thay vào đó, bạn chỉ có thể thêm chuỗi bộ lọc theo cách cũ đơn giản bằng cách đăng ký DelegatingFilterProxy làm bộ lọc. Tất nhiên, bạn sẽ cần phải duy trì thứ tự bằng cách thêm Bộ lọc Cors trước khi thêm chuỗi bộ lọc bảo mật mùa xuân.

Bằng cách này, bạn sẽ có thể sử dụng phần mềm CorsFilter (chỉ bằng cách thêm tham số init) đi kèm với gói org.apache.catalina.filters.Dù sao, bạn có thể gắn bó với cấu hình của riêng bạn quá! :)

+0

Xin chào, tôi quan tâm đến điều này. Tôi đang gặp rắc rối với ứng dụng của nhà cung cấp và tôi cần thêm cors Bạn có thể hướng dẫn cho tôi một chút.Bạn có ý nghĩa gì bởi: (chỉ bằng cách thêm các tham số init) Tôi muốn sử dụng bộ lọc cors được cung cấp của tomcat như ý của bạn. Bạn có thể vui lòng cung cấp cho tôi các bước không? – MaatDeamon

Các vấn đề liên quan