2017-02-03 11 views
1

Angular2アプリは、X-AUTH-TOKENヘッダ値を持つHTTP GET要求をSpringブートに送信しています。毎回request.getHeader("X-AUTH-TOKEN")nullを返します。SpringブートCORS設定が承認ヘッダを受け付けていません

ARCクライアントまたは他のレストクライアントからリクエストを送信すると、面白いことに、うまく動作します。

Angular HTTP GETリクエストがJWTトークンを送信していることを確認するために多大な時間を費やしました。

角度コード

getCandidatesByUserId(userId: number): Observable<Candidate[]> { 
    let headers = new Headers({ 'X-AUTH-TOKEN': 'let-jwt-test-token-in' }); 
    console.log('Token is '+ headers.get('X-AUTH-TOKEN')); 
    return this.http.get(this.url+userId+'/candidates', { 
     headers: headers 
    }) 
     .map((response: Response) => <Candidate[]> response.json()) 
     .do(data => console.log('All: '+ JSON.stringify(data))) 
     .catch(this.handleError); 
    } 

JWTFilter

@Override 
    public void doFilter(ServletRequest request, ServletResponse res, FilterChain filterChain) 
      throws IOException, ServletException { 

     try { 
      final HttpServletResponse response = (HttpServletResponse) res; 
      response.setHeader("Access-Control-Allow-Origin", "*"); 
      response.setHeader("Access-Control-Allow-Credentials", "true"); 
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); 
      response.setHeader("Access-Control-Max-Age", "3600"); 
      response.setHeader("Access-Control-Allow-Headers", "X-AUTH-TOKEN, Content-Type, Accept"); 
      response.setHeader("Access-Control-Expose-Headers", "X-AUTH-TOKEN, Content-Type"); 

      HttpServletRequest httpRequest = (HttpServletRequest) request; 
      Map<String, String> blackListedTokenMap = 
        (Map<String, String>) ((HttpServletRequest) request) 
          .getSession() 
          .getServletContext() 
          .getAttribute(WebAppListener.TOKEN_BLACK_LIST_MAP); 
      String authToken = authenticationService.getToken(httpRequest); 
      if (authToken != null && blackListedTokenMap.containsValue(authToken)) { 
       throw new RuntimeException("token invalidated"); 
      } 
      UserAuthentication authentication = (UserAuthentication) authenticationService.getAuthentication(httpRequest); 
      SecurityContextHolder.getContext().setAuthentication(authentication); 
      filterChain.doFilter(request, response); 
      SecurityContextHolder.getContext().setAuthentication(null); 
     } catch (RuntimeException e) { 
      ((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED); 
     } 
    } 

SpringSecurityConfig

@Override 
    protected void configure(HttpSecurity http) throws Exception { 

     http 
      .csrf() 
       .csrfTokenRepository(new HttpSessionCsrfTokenRepository()) 
       .requireCsrfProtectionMatcher(new AntPathRequestMatcher("*/*")); 
     http 
      .exceptionHandling() 
       .and() 
      .anonymous() 
       .and() 
      .servletApi() 
       .and() 
      .headers() 
       .cacheControl(); 

     http 
       //.addFilterBefore(corsFilter, ChannelProcessingFilter.class) 
      .authorizeRequests() 
       .antMatchers("/resources/**").permitAll()// allow for static resources 
       .antMatchers("/signup").permitAll() 
       .antMatchers("/forgot").permitAll() 
       .antMatchers("/login").permitAll() 
       .antMatchers("/reset").permitAll() 
       .antMatchers("/health").permitAll() 
       .antMatchers("/hello").permitAll() 
       .antMatchers("/").permitAll() 
       .antMatchers("/reset_pw").permitAll() 
       .anyRequest().authenticated() 
       .and() 
      .addFilterAfter(new JJWTFilter(tokenAuthenticationService), 
         UsernamePasswordAuthenticationFilter.class); 
    } 

コンソールログ enter image description here

+1

スプリングブーツを使用していますか?私は最近同様の問題を抱えていました。フィルタでAuthorizationヘッダーを取得していたアプリケーションが壊れました。それはnullだった。 @EnableWebMvcアノテーションがそれを台無しにしていると判断しました。 –

+0

@LucasHoltはい。私はバックエンドに 'SpringBoot'を使用していますが、' @ EnableWebMvc'はどこにも使用していません。 –

+0

こんにちは、これに関するニュース?私は同じ問題を抱えています。 郵便配達員と電話をかけることはできますが、角度のあるアプリではできません。 – Castelmager

答えて

0

私はで解決:あなたはこのクラスを定義して、ブート春のクラスに@ComponentScan(basePackageClasses= CorsConfig.class)

それともブートクラスの内部で上記の方法を使用するを追加することができます

//Define class with this annotation 

@Configuration 

public class CorsConfig { 

    @Bean 
    public FilterRegistrationBean corsFilter() { 
     UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
     CorsConfiguration config = new CorsConfiguration(); 
     config.setAllowCredentials(true); 
     config.addAllowedOrigin("*"); 
     config.addAllowedHeader("*"); 
     config.addAllowedMethod("OPTIONS"); 
     config.addAllowedMethod("HEAD"); 
     config.addAllowedMethod("GET"); 
     config.addAllowedMethod("PUT"); 
     config.addAllowedMethod("POST"); 
     config.addAllowedMethod("DELETE"); 
     config.addAllowedMethod("PATCH"); 
     source.registerCorsConfiguration("/**", config); 
     // return new CorsFilter(source); 
     final FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); 
     bean.setOrder(0); 
     return bean; 
    } 

    @Bean 
    public WebMvcConfigurer mvcConfigurer() { 
     return new WebMvcConfigurerAdapter() { 
      public void addCorsMappings(CorsRegistry registry) { 
       registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "GET", "OPTIONS"); 
      } 
     }; 
    } 
} 

次に動作するはずです。

関連する問題