2017-05-31 36 views
4

我有一個帶有Angular 4 web前端的Spring Boot REST API。我對這兩種框架都非常滿意。一個不斷出現的問題與CORS請求有關。這感覺就像一場鼴鼠遊戲。每當我擠壓一個問題時,另一個問題很快就會出現,並且會毀掉我的週末。 我現在可以向我的spring boot api提出請求,而不會出現問題。但是,當我想從我的角度網站的響應中檢索我的標題時,只有5個標題可用,其中大部分都缺少,包括我最感興趣的ETag標題。 我讀了一些SO帖子,聲稱我只需要在我的角度http調用中添加一個請求標頭,以公開我需要的標頭(順便說一句,在調試控制檯中,我會看到所期望的所有標頭)。 從Angular2 Http Response missing header key/values的建議是,增添headers.append('Access-Control-Expose-Headers', 'etag');Angular 4 http call過濾掉了我的大部分API響應頭文件

我試過,但我得到以下errror:「請求頭字段訪問控制展露報頭沒有被訪問控制允許報頭在預檢響應允許」

這個消息讓我困惑,說實話。我在春季啓動時調整了一些CORS設置,但無濟於事。

我不知道該去哪裏。我幾乎考慮從java + spring啓動切換回PHP(畏縮),因爲我從來沒有這樣做過,我無法用PHP解決的噩夢。

如果您有任何建議,請幫助我。

用於我的角前端相關的代碼是下面:

import {Injectable} from '@angular/core'; 
 
import {Http, RequestOptions, Response} from '@angular/http'; 
 
import {Post} from '../class/post'; 
 
import {Observable} from 'rxjs/Rx'; 
 
import 'rxjs/add/operator/mergeMap'; 
 
import 'rxjs/add/operator/map'; 
 

 

 
@Injectable() 
 
export class PostDaoService { 
 

 
    private jwt: String; 
 

 
    private commentsUrl = 'http://myapidomain/posts'; 
 

 
    private etag: string; 
 

 
    constructor(private http: Http, private opt: RequestOptions) { 
 
    // tslint:disable-next-line:max-line-length 
 
    this.jwt = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJQYXNjYWwiLCJ1c2VySWQiOiIxMjMiLCJyb2xlIjoiYWRtaW4ifQ.4D9TUDQAgIWAooyiMN1lV8Y5w56C3PKGzFzelSE9diqHMik9WE9x4EsNnEcxQXYATjxAZovpp-m72LpFADA'; 
 
    } 
 

 
    getPosts(trigger: Observable<any>): Observable<Array<Post>> { 
 
    this.opt.headers.set('Authorization', 'Bearer ' + this.jwt); 
 
    this.opt.headers.set('Content-Type', 'application/json'); 
 

 
    this.opt.headers.set('Access-Control-Expose-Headers', 'etag'); 
 
    if (this.etag !== null) { 
 
     this.opt.headers.set('If-None-Match', this.etag); 
 
    } 
 

 
    return trigger.mergeMap(() => 
 
     this.http.get(this.commentsUrl) 
 
     .map((response) => { 
 
      if (response.status === 304) { 
 
      alert('NO CHANGE TO REPOURCE COLLECTION'); 
 
      } else if (response.status === 200) { 
 
      console.log(response.headers); 
 
      console.log(response.text()); 
 
      return response.json()._embedded.posts as Post[]; 
 
      } 
 
     } 
 
    )); 
 
    } 
 

 
    submitPost(): Promise<Object> { 
 
    this.opt.headers.set('Authorization', 'Bearer ' + this.jwt); 
 
    this.opt.headers.set('Content-Type', 'application/json'); 
 
    return this.http.post(this.commentsUrl, JSON.stringify({text: 'some new text'})) 
 
     .toPromise() 
 
     .then(response => response.json()) 
 
     .catch(); 
 
    } 
 

 
}

和應用類(CORS配置)從彈簧引導程序是如下:

@SpringBootApplication 
@EnableJpaRepositories("rest.api.repository") 
@EnableMongoRepositories("rest.api.repository") 
@EnableTransactionManagement 
@EnableConfigurationProperties 
@EnableCaching 
public class Application extends SpringBootServletInitializer{ 

public static final long LOGGED_IN_USER = 1L; 

public static void main(String[] args) { 
    SpringApplication.run(Application.class, args); 

} 

@Override 
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 

    return application.sources(Application.class); 
} 

@Bean 
public FilterRegistrationBean corsFilter() { 
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
    CorsConfiguration config = new CorsConfiguration(); 
    config.setAllowCredentials(true); 
    config.addAllowedOrigin("*"); 
    config.addAllowedHeader("Access-Control-Expose-Headers"); 
    config.addAllowedHeader("X-Requested-With"); 
    config.addAllowedHeader("Authorization"); 
    config.addAllowedHeader("Content-Type"); 
    config.addAllowedHeader("If-None-Match"); 
    config.addAllowedHeader("Access-Control-Allow-Headers"); 

    config.addExposedHeader("Access-Control-Allow-Origin"); 
    config.addExposedHeader("Access-Control-Allow-Headers"); 
    config.addExposedHeader("ETag"); 
    config.addAllowedMethod("GET"); 
    config.addAllowedMethod("POST"); 
    config.addAllowedMethod("PUT"); 
    config.addAllowedMethod("DELETE"); 
    config.addAllowedMethod("OPTIONS"); 
    config.addAllowedMethod("HEAD"); 

    source.registerCorsConfiguration("/**", config); 
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); 
    bean.setOrder(0); 
    return bean; 
} 
} 

和我的控制器:

@RepositoryRestController 
@CrossOrigin(methods = {RequestMethod.GET, 
    RequestMethod.POST, 
    RequestMethod.PUT, 
    RequestMethod.DELETE, 
    RequestMethod.OPTIONS, 
    RequestMethod.HEAD}) 
public class PostController { 

private PostRepository postRepository; 
private UserRepository userRepository; 
private LikeRepository likeRepository; 
private DislikeRepository dislikeRepository; 

@Autowired 
PagedResourcesAssembler pagedResourcesAssembler; 

protected PostController() { 
} 

@Autowired 
public PostController(PostRepository postRepository, UserRepository userRepository, LikeRepository likeRepository, DislikeRepository dislikeRepository) { 
    this.postRepository = postRepository; 
    this.userRepository = userRepository; 
    this.likeRepository = likeRepository; 
    this.dislikeRepository = dislikeRepository; 
} 

@ResponseBody 
@RequestMapping(value = "/posts", method = RequestMethod.GET) 
public ResponseEntity<PagedResources<PersistentEntityResource>> getAll(HttpRequest request, 
                     Pageable pageable, 
                     PersistentEntityResourceAssembler resourceAssembler) { 
     Page<Post> page = postRepository.findAll(pageable); 
     return ResponseEntity 
       .ok() 
       .cacheControl(CacheControl.maxAge(5, TimeUnit.SECONDS)) 
       .eTag(String.valueOf(page.hashCode())) 
       .body(pagedResourcesAssembler.toResource(page, resourceAssembler)); 

} 

@ResponseBody 
@RequestMapping(value = "/posts", method = RequestMethod.POST) 
public ResponseEntity<PersistentEntityResource> sendPost(@RequestBody Post post, 
                 PersistentEntityResourceAssembler resourceAssembler, 
                 UriComponentsBuilder b) { 
    User sender = userRepository.findOne(1L); 
    URI loc = null; 
    post.setSender(sender); 
    post = postRepository.save(post); 

    UriComponents uriComponents = 
      b.path("/posts/{id}").buildAndExpand(post.getIdentify()); 

    HttpHeaders headers = new HttpHeaders(); 

    return ResponseEntity 
      .ok() 
      .cacheControl(CacheControl.maxAge(5, TimeUnit.SECONDS)) 
      .location(uriComponents.toUri()) 
      .eTag(String.valueOf(post.getVersion())) 
      .body(resourceAssembler.toFullResource(post)); 
} 

@ResponseBody 
@RequestMapping(value = "/posts/{id}", method = RequestMethod.PUT) 
public PersistentEntityResource edit(@PathVariable(value = "id") long id, @RequestBody Post post, PersistentEntityResourceAssembler resourceAssembler) { 
    Post editedPost = postRepository.findOne(id); 
    editedPost.setCreated(post.getCreated()); 
    editedPost.setText(post.getText()); 
    postRepository.save(editedPost); 
    return resourceAssembler.toFullResource(editedPost); 
} 

@ResponseBody 
@RequestMapping(value = "/posts/{id}/likes", method = RequestMethod.POST) 
public PersistentEntityResource likePost(@PathVariable(value = "id") long id, PersistentEntityResourceAssembler resourceAssembler) { 
    final boolean isAlreadyLiked = false; 

    User userWhoLikesIt = userRepository.findOne(1L); 
    Post post = postRepository.findOne(id); 
    post.setLiked(post.getLiked() + 1); 
    Likey like = new Likey(userWhoLikesIt); 
    likeRepository.save(like); 
    return resourceAssembler.toFullResource(like); 
} 

@ResponseBody 
@RequestMapping(value = "/posts/{id}/dislikes", method = RequestMethod.POST) 
public PersistentEntityResource dislikePost(@PathVariable(value = "id") long id, PersistentEntityResourceAssembler resourceAssembler) { 
    User userWhoDislikesIt = userRepository.findOne(1L); 
    DisLike dislike = new DisLike(userWhoDislikesIt); 
    dislikeRepository.save(dislike); 
    return resourceAssembler.toFullResource(dislike); 
} 

@ResponseBody 
@RequestMapping(value = "/posts/{id}/likes", method = RequestMethod.GET) 
public ResponseEntity<PagedResources<PersistentEntityResource>> getLikes(HttpRequest request, 
                     Pageable pageable, 
                     PersistentEntityResourceAssembler resourceAssembler) { 
    Page<Likey> page = likeRepository.findAll(pageable); 
    return ResponseEntity 
      .ok() 
      .cacheControl(CacheControl.maxAge(5, TimeUnit.SECONDS)) 
      .eTag(String.valueOf(page.hashCode())) 
      .body(pagedResourcesAssembler.toResource(page, resourceAssembler)); 

} 

@ResponseBody 
@RequestMapping(value = "/posts/{id}/dislikes", method = RequestMethod.GET) 
public ResponseEntity<PagedResources<PersistentEntityResource>> getDislikes(HttpRequest request, 
                     Pageable pageable, 
                     PersistentEntityResourceAssembler resourceAssembler) { 
    Page<DisLike> page = dislikeRepository.findAll(pageable); 
    return ResponseEntity 
      .ok() 
      .cacheControl(CacheControl.maxAge(5, TimeUnit.SECONDS)) 
      .eTag(String.valueOf(page.hashCode())) 
      .body(pagedResourcesAssembler.toResource(page, resourceAssembler)); 

} 

}

有沒有人有任何想法我在做什麼錯在這裏?

編輯:我也想知道如果我的WebSecurityConfig.java可能與此有關,因爲我不得不在這裏具體驗證OPTIONS請求,以避免以前的預檢問題:

@Configuration 
@EnableWebSecurity 
@EnableAutoConfiguration 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
private JwtAuthenticationEntryPoint unauthorizedHandler; 

@Autowired 
private JwtAuthenticationProvider authenticationProvider; 

@Bean 
@Override 
public AuthenticationManager authenticationManager() throws Exception { 

    return new ProviderManager(Arrays.asList(authenticationProvider)); 
} 

@Bean 
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception { 
    JwtAuthenticationTokenFilter authenticationTokenFilter = new JwtAuthenticationTokenFilter(); 
    authenticationTokenFilter.setAuthenticationManager(authenticationManager()); 
    authenticationTokenFilter.setAuthenticationSuccessHandler(new JwtAuthenticationSuccessHandler()); 
    return authenticationTokenFilter; 
} 

@Override 
protected void configure(HttpSecurity httpSecurity) throws Exception { 
    httpSecurity 
      // we don't need CSRF because our token is invulnerable 
      .csrf().disable() 
      // All urls must be authenticated (filter for token always fires (/**) 
      .authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").authenticated() 
      .and() 
      // Call our errorHandler if authentication/authorisation fails 
      .exceptionHandling().authenticationEntryPoint(unauthorizedHandler) 
      .and() 
      // don't create session 
      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); //.and() 
    // Custom JWT based security filter 
    httpSecurity 
      .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 

    // disable page caching 
    httpSecurity.headers().cacheControl(); 

} 

}

回答

0

你必須讓你的Spring代碼發送Access-Control-Expose-Headers作爲響應頭 - 就我所知,這是你已經擁有的config.addExposedHeader(…)代碼應該爲你做的。但是,如果你在響應中沒有看到Access-Control-Expose-Headers標題,那麼我猜配置代碼不能按預期工作,你需要調試它。

Angular2 Http Response missing header key/values的建議是,增添headers.append('Access-Control-Expose-Headers', 'etag');

這一建議是錯誤的,因爲它只是造成Access-Control-Expose-Headers請求頭被添加到該請求從您的客戶端前端代碼發送。

但是Access-Control-Expose-Headers響應標題說明您發出請求的服務器必須發送響應。

我試過這個,但是我得到下面的錯誤:「請求標頭字段Access-Control-Expose-Headers在預檢響應中不被Access-Control-Allow-Headers所允許。」

對,這是因爲您的客戶端前端代碼不應該發送該標頭。

+0

我目前還沒有機會調試這個問題,但是您剛剛確認了很多關於圍繞這些頭文件的目的以及我的CORS安裝配置在春天配置中發現的建議的許多懷疑。我有許多圍繞CORS的問題,這似乎主要歸因於spring-jwt-security與跨源支持的結合。謝謝你,我今晚會調查一下。 – gezinspace