2016-06-28 118 views
1

我正在用Spring-boot(在http://localhost:8080)和angular(在http://localhost:80)上構建一個應用程序。彈簧安全的CORS問題

前端和後端代碼由2個不同的服務器提供服務。爲了避免CORS問題,我過去使用了一箇中間的nginx服務器,但我對這個解決方案不再滿意。因此,我必須允許CORS。

我允許CORS全球與線:

@Configuration 
public class WebMvcConfiguration extends WebMvcConfigurerAdapter { 

    @Override 
    public void addCorsMappings(CorsRegistry registry) { 
    registry.addMapping("/**") 
     .allowedOrigins("http://localhost") 
     .allowCredentials(true) 
    ; 
    } 
} 

作品爲每路線除了認證路線這與春季安全處理:

public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Override 
    public void configure(HttpSecurity http) throws Exception { 
    http 
     .formLogin() 
     .successHandler(successHandler()) 
     .failureHandler(failureHandler()) 
    //[...] 
    } 

    private AuthenticationSuccessHandler successHandler() { 
    return (httpServletRequest, httpServletResponse, authentication) -> 
     httpServletResponse.setStatus(HttpServletResponse.SC_OK); 
    } 

    private AuthenticationFailureHandler failureHandler() { 
    return (httpServletRequest, httpServletResponse, e) -> { 
     httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 
    }; 
} 

這裏是在前端部分發送請求的代碼:

$http.post('http://localhost:8080/api/login', $.param({'username': username, 'password': password}), 
      {headers: {'content-type': 'application/x-www-form-urlencoded'}} 
).then(function() {}) 
.catch(function(error) {}; 

如果我輸入正確的密碼,那麼http響應代碼(我可以在Chrome控制檯中看到)是200,但我仍然可以訪問catch塊(error.status = -1),我可以看到此錯誤消息在控制檯中:

XMLHttpRequest無法加載http://localhost:8080/api/login。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許訪問原產地'http://localhost'。

如果我輸入了錯誤的密碼,我也與此錯誤消息到達catch塊:

的XMLHttpRequest無法加載http://localhost:8080/api/login。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許訪問原產地'http://localhost'。該響應具有HTTP狀態代碼401.

我還注意到,當我調用身份驗證端點時,CORS響應標頭丟失。

任何想法?

編輯:它工作如果我手動添加標頭自定義成功處理程序。我寧願Spring-security可以考慮全局CORS配置。

+0

http://stackoverflow.com/questions/35035055/spring-boot-and-cors/35040051#35040051大概這可以節省您的時間:) –

回答

0

根據我的經驗,您需要在CORS中包含端口號,瀏覽器中的錯誤消息有點誤導。

您可以通過檢查網絡並檢查請求標頭的Origin字段來驗證。響應頭中的值Access-Control-Allow-Origin必須與包含協議和端口的值完全匹配。

0

有完全相同的問題你可以做兩件事,

  1. @CrossOrigin(origins = "http://localhost:8080")將此添加到服務方法。這背後的想法是您通過服務本身啓用CORS請求。
  2. 使用JSONP,但這有一定的侷限性。我也沒有成功實施它,所以我使用了上述選項。