복붙노트

[SPRING] Spring Security 3.2에서 Access-Control-Origin 필터를 문제없이 설치하는 방법

SPRING

Spring Security 3.2에서 Access-Control-Origin 필터를 문제없이 설치하는 방법

아약스 로그인 요청을 할 수 있도록 스프링 보안 3.2로 스프링 서버를 설정하려고합니다.

나는 Spring Security 3.2 비디오와 몇 개의 게시물을 따라 갔지만 문제는

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

로그인 요청 (아래 참조).

CORSFilter 설치 프로그램을 만들었고 응답에 적절한 헤더를 추가하여 시스템의 보호되지 않은 리소스에 액세스 할 수 있습니다.

내 추측으로는 보안 필터 체인에 CORSFilter를 추가하지 않고 있거나 체인에서 너무 늦을 수 있습니다. 어떤 아이디어라도 감사 할 것입니다.

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 '/'");
        }
    }

보안 WebAppInitializer :

public class SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer {
}

SecurityConfig :

/ api / users에 대한 요청이 잘 작동하고 Access-Control-Allow 헤더가 추가되었습니다. 나는 이것이 사실이 아닌지 확인하기 위해 csrf와 헤더를 비활성화했다.

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

로그인 요청 :

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

해결법

  1. ==============================

    1.내가 누락 한 것은 보안 구성을 구성 할 때 AddFilterBefore뿐이었습니다.

    내가 누락 한 것은 보안 구성을 구성 할 때 AddFilterBefore뿐이었습니다.

    그래서 최종 버전은 다음과 같습니다.

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

    그리고 WebAppInitializer에서 CORSFilter를 제거하십시오.

  2. ==============================

    2.나는 당신의 질문에 대답 하기엔 너무 늦었다 고 생각하지만, 공유 할 가치가 있다고 생각합니다. 초기 설정에서 스프링 컨 시큐리티 이니셜 라이저 구성 메타 데이터를 루트 컨텍스트에 등록했습니다 :

    나는 당신의 질문에 대답 하기엔 너무 늦었다 고 생각하지만, 공유 할 가치가 있다고 생각합니다. 초기 설정에서 스프링 컨 시큐리티 이니셜 라이저 구성 메타 데이터를 루트 컨텍스트에 등록했습니다 :

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

    이렇게 할 수 있으면 보안 필터 체인을 필요하지 않은 웹 응용 프로그램 컨텍스트와 연결하므로 필요하지 않습니다. 대신 DelegatingFilterProxy를 필터로 등록하여 일반 오래된 방법으로 필터 체인을 추가 할 수 있습니다. 물론 스프링 보안 필터 체인을 추가하기 전에 Cors Filter를 추가하여 주문을 유지해야합니다.

    이렇게하면 org.apache.catalina.filters 패키지와 함께 제공되는 CorsFilter 스톡 (init 매개 변수를 추가하는 것만으로)을 사용할 수 있습니다. 어쨌든, 당신은 당신 자신의 구성을 고수 할 수 있습니다! :)

  3. from https://stackoverflow.com/questions/22886186/how-to-setup-access-control-allow-origin-filter-problematically-in-spring-securi by cc-by-sa and MIT license