2017-08-25 65 views
1

角應用,(在的WebPack開發服務器執行),休息API調用(從角)返回401

這讓REST調用部署在碼頭有Spring應用程序(啓用了春季安全/ BASIC身份驗證) 。

當調用http://localhost:8085/myapi/api/login通過角,響應是:401未經授權 (請求方法是OPTIONS,雖然被指定爲POST)

試過大多數解決方案張貼與此相關的(使能/從角發送CORS標頭,春季安全和web.xml(碼頭)側

需要什麼樣的

錯誤在Chrome:?響應預檢申請未通過訪問控制檢查:沒有「訪問控制允許來源」標頭出現在所請求的資源

let headers = new Headers(); 
headers.append("Authorization", "Basic " + btoa("test_user:test_user")); 
headers.append("X-Requested-With", "XMLHttpRequest"); 
headers.append("withCredentials", "true"); 
//headers.append("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE"); 
//headers.append("Access-Control-Allow-Origen", "*"); 

let options = new RequestOptions({headers: headers}); 
this.http.post("http://localhost:8085/myapi/api/services/login", 
       JSON.stringify({}), options); 

春季安全

<sec:http auto-config="true" use-expressions="true" 
entry-point-ref="authenticationEntryPoint"> 
    <sec:form-login /> 
    <sec:http-basic /> 
    <sec:logout /> 
    <sec:intercept-url pattern="/**" access="permitAll" /> 
    <!-- corsHandler: filter (OncePerRequestFilter) that adds Access-Control-Allow-Origin header --> 
    <sec:custom-filter ref="corsHandler" position="PRE_AUTH_FILTER"/> 
    <sec:cors /> 
</sec:http> 

web.xml

<filter> 
    <filter-name>cross-origin</filter-name> 
    <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class> 
    <init-param> 
     <param-name>allowedOrigins</param-name> 
     <param-value>*</param-value> 
    </init-param> 
    <init-param> 
     <param-name>allowedMethods</param-name> 
     <param-value>GET,POST,OPTIONS,DELETE,PUT,HEAD</param-value> 
    </init-param> 
    <init-param> 
     <param-name>allowedHeaders</param-name> 
     <param-value>Origin,Content-Type,Accept,authorization,X-Requested-With</param-value> 
    </init-param> 
</filter> 
<filter-mapping> 
    <filter-name>cross-origin</filter-name> 
    <url-pattern>*</url-pattern> 
</filter-mapping> 

的WebPack服務器:

devServer: { 
    historyApiFallback: true, 
    stats: 'minimal', 
     headers: { 
      'Access-Control-Allow-Origin': '*' 
     } 
    } 

有過濾器(Servlet過濾器)和Spring攔截設置中添加訪問控制允許,俄頭,但都不執行。

回答

0

最終的解決辦法是在發展的WebPack服務器

代理創建代理避免CORS問題(代理:{...})。其餘api的URL已更新到角度應用程序正在運行的相同機器: this.http.post(「http://localhost:/myapi/api/services/login」,...):

的WebPack代理:

devServer: { 
    historyApiFallback: true, 
    stats: 'minimal', 
    headers: { 
     'Access-Control-Allow-Origin': '*' 
    }, 
    proxy: { 
     '/myapi/api/**': { 
      target: 'http://localhost:8085', 
      secure: false    
     } 
    } 
} 

從角,需要針對其餘映射方法與認證頭的HTTP通話。

@PostMapping("/login") 
public ResponseEntity login() { 
    return new ResponseEntity<>(HttpStatus.OK); 
} 

調用此方法其餘(通過代理)似乎做工精細一次CORS問題鴕鳥政策存在。

鴕鳥政策明白爲什麼CORS配置並沒有在這種情況下工作: 最相關的上述問題給出CORS的代碼是沒有必要這個解決方案