2017-08-26 74 views
4

我試圖使用新發布的HttpClientAngular 4實施基本授權。解決:角4.3 HTTPClient基本授權不起作用

我在嘗試連接到在Tomcat上運行的Spring應用程序,並在其中暴露了REST API。

我在LoginComponent下面的代碼:

onSubmit(user){ 
    console.log(user); 
    const body = JSON.stringify({username: user.userName, password: user.password}); 

    let headers = new HttpHeaders(); 
    headers.append("Authorization", "Basic " + btoa("username:password")); 
    headers.append("Content-Type", "application/x-www-form-urlencoded"); 

    this.http.post('my url here',body, {headers: headers}).subscribe(response => { 
     console.log(response); 
    }, err => { 
     console.log("User authentication failed!"); 
    }); 
} 

但是,請求不添加Authorization頭都沒有。

這是從Chrome工具Network標籤:

enter image description here

我在做什麼錯? 我該如何做這項工作?


更新1:它仍然沒有工作:

我改變了我的兩行如下:

headers = headers.append("Authorization", "Basic " + btoa("username:password")); 
headers = headers.append("Content-Type", "application/x-www-form-urlencoded"); 

我得到的請求頭如預期。這是Chrome

enter image description here

然而,後調用仍然失敗。

在服務器端,我的代碼是:

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { 
    String authCredentials = request.getHeader("Authorization"); 

    if(authCredentials == null) { 
     logger.info("Request with no basic auth credentials {}", request.getRequestURL()); 
     response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 
     return; 
    } 

    // do my stuff 
} 

呼叫不會達到do my stuffauthCredentialsnull

這是chrome

enter image description here

如何進行?


更新2:它的工作:

我不得不做這兩個步驟:

1)我不得不把headers線改變什麼,我在更新1那樣,因爲HttpHeaders是不可改變的。

headers = headers.append("Authorization", "Basic " + btoa("username:password")); 
headers = headers.append("Content-Type", "application/x-www-form-urlencoded"); 

2)現在,根據您的需要,你有兩個選擇:

一)使用代理作爲解釋here解決CORS問題不改變你的服務器端。

b)按照here的說明更新服務器端,並在下面的一些答案中更改彈簧配置。

+0

從包你進口'http' - '@角/普通/ http'或'@角/ http' –

+0

@AjitSoman:@角/普通/ HTTP ... – Nik

+0

難道Ben的回答工作你呢?你有沒有在控制檯上看到有關Cors的錯誤? –

回答

5

HttpHeaders是不可變的,所以您需要分配函數的結果來覆蓋每個調用的headers對象。

let headers = new HttpHeaders(); 
headers = headers.append("Authorization", "Basic " + btoa("username:password")); 
headers = headers.append("Content-Type", "application/x-www-form-urlencoded"); 

來源:Angular Docs

+0

「分配函數的結果以覆蓋每個調用的標頭對象」。你能詳細解釋一下嗎? – Nik

+0

查看代碼,而不是簡單的'headers.append()',因爲'headers.append()'創建了一個新的頭對象,所以您必須執行headers = headers.append()'使用 –

+1

哦!抱歉!現在注意到了..我以爲你只是粘貼了我的兩行!將嘗試它..謝謝! – Nik

1

嗨能將你的後端CORS配置

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.web.cors.CorsConfiguration; 
import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 
import org.springframework.web.filter.CorsFilter; 

@Configuration 
public class RestConfig { 
    @Bean 
    public CorsFilter corsFilter() { 
     UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
     CorsConfiguration config = new CorsConfiguration(); 
     config.setAllowCredentials(true); 
     config.addAllowedOrigin("*"); 
     config.addAllowedHeader("*"); 
     config.addAllowedMethod("OPTIONS"); 
     config.addAllowedMethod("GET"); 
     config.addAllowedMethod("POST"); 
     config.addAllowedMethod("PUT"); 
     config.addAllowedMethod("DELETE"); 
     source.registerCorsConfiguration("/**", config); 
     return new CorsFilter(source); 
    } 
} 

你的角度要求應該是這樣的,

import { Http , Headers, Response } from '@angular/http'; 
let headers = new Headers(); 
headers.append("Authorization", "Basic " + btoa("username:password")); 
headers.append("Content-Type", "application/x-www-form-urlencoded"); 

您還可以檢查githup回購樣品演示 spring mvc with angular2/4

0

使用RequestOptions爲您的發佈請求設置標題。

import { Http,Headers,RequestOptions } from '@angular/http'; 
    .. 
    .. 
    let headers = new Headers(); 
    headers.append("Authorization", "Basic " + btoa("username:password")); 
    headers.append("Content-Type", "application/x-www-form-urlencoded"); 

    let options = new RequestOptions({ headers: headers }); 
    this.http.post('my url here',body, options).subscribe(response => { 
      console.log(response); 
     }, err => { 
      console.log("User authentication failed!"); 
     }); 
+0

謝謝..但我試圖使用新版本HttpClient(Angular 4.3).. – Nik

+0

本的答案沒有工作..我已經更新了這個問題.. – Nik

+0

RequestOptions不能使用HttpHeaders從@ angular/common/http – Nik