13

ajax oturum açma isteği yapabilmek için Spring sunucumu Spring Security 3.2 ile kurmaya çalışıyorum. Spring Security 3.2'de Access-Control-Allow-Origin süzgeci sorunlu olarak nasıl ayarlanır?

Ben mesajların Spring Security 3.2 video ve çift izledi ancak sorun (aşağıya bakınız) giriş talepleri için

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

alıyorum olmasıdır.

Bir CORSFilter kurulumu oluşturdum ve sistemimde korumasız kaynaklara, yanıta eklenen uygun başlıklarla erişebiliyorum.

Tahminim, güvenlik filtresi zincirine CORSFilter eklemiyorum ya da zincirde çok geç kalmış olabilir. Herhangi bir fikir takdir edilecektir.

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: /api'sine

İstek/kullanıcıların - iyi çalışın ve Access-Control-Allow üstbilgileri eklenir. Ben özürlü csrf ve başlıkları sadece bu durumda

@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 olmadığından emin olmak için:

@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() {} 
} 

Giriş İsteği:

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

Yay güvenlik yapılandırmanızı ekleyebilir misiniz? –

cevap

17

tek şey eksik olan Güvenlik yapılandırmasını yapılandırırken AddFilterBefore.

Yani son hali vardı:

@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(); 

Ve ben senin soruya cevap vermek biraz çok geç olduğunu biliyorum WebAppInitializer

+0

Spring 4.2 :(ile çalışıyor görünmüyor. ( – froginvasion

+0

Spring boot 1.4.0 ile çalışmıyorum. – WhiteWater

0

gelen CORSFilter kaldırmak ancak paylaşmaya değer olabileceğini düşündüm. Bunu yapmanın zaman çift web uygulama bağlamıyla güvenlik filtresi zincirini olacak şekilde

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

, sen gerekmez: İlk yapılandırmada kök bağlamıyla Bahar Güvenlik başlatıcı yapılandırma meta kayıtlı vardı bu gerekli değildir. Bunun yerine, filtre zincirini DelegatingFilterProxy'yi bir süzgeç olarak kaydederek yalnızca eski bir şekilde ekleyebilirsiniz. Elbette, yaylı güvenlik filtresi zincirini eklemeden önce Cors Filtresini ekleyerek siparişi korumanız gerekecektir.

Bu şekilde, org.apache.catalina.filters paketi ile birlikte gelen CorsFilter (yalnızca init paramlerini ekleyerek) stokunu kullanabilirsiniz.Neyse, kendi konfigürasyonunuza da bağlı kalabilirsiniz! :)

+0

Hey, bununla ilgileniyorum. Bir satıcı uygulamasıyla başım dertte ve korsanlar eklemem gerekiyor bana biraz rehberlik eder misiniz, ne demek istiyorsun: (sadece init paramler ekleyerek) tomcat'in sağladığı cors-filter'i kullanmak istediğin gibi kullanmak istiyorum. – MaatDeamon

İlgili konular