2017-10-19 66 views
1

我有一個認證攔截器,但是,我希望當用戶訪問像確認賬號密碼等,這並不需要用戶身份驗證的組件這個攔截過濾請求並沒有被應用。如何去做任何的例子嗎?以下是auth攔截器的邏輯:過濾請求 - 角4.3+

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    // Get the auth token from the service. 
    let authToken = this.authService.getToken(); 
    let authHeader = 'Bearer ' + authToken; 

    //For requests that are retried, we always want a fresh copy, else the request will have headers added multiple times. 
    //So Clone the request before adding the new header. 
    //NOTE: the cache and pragma are required for IE that will otherwise cache all get 200 requests. 
    const authReq = request.clone({ 
     setHeaders: { 
     Authorization: authHeader, 
     'Cache-Control': 'no-cache', 
     'Pragma': 'no-cache' 
     } 
    }); 
    // Pass on the cloned request instead of the original request. 
    return next.handle(authReq); 
} 

回答

0

對於這種情況,請求的URL有幫助。

假設您的身份驗證網址類似於auth/login or auth/refreshToken,並且您的資源API類似於api/users, api/users/123, api/addUser,那麼您可以通過if條件來檢查請求的內容。 URL匹配的

例子: -

if (request.url.match(/api\//)) { // api call 
    console.log('api call detected.'); 
    let authToken = this.authService.getToken(); 
    let authHeader = 'Bearer ' + authToken; 
    const authReq = request.clone({ 
    setHeaders: { 
     Authorization: authHeader, 
     'Cache-Control': 'no-cache', 
     'Pragma': 'no-cache' 
    } 
    }); 
    return next.handle(authReq); 
} 
else{ // auth call - you can put esle if conditions if you have more such pattern 
console.log('auth call detected.'); 
    return next.handle(request); 
}  

現在authentication headers將只被添加到您的API調用(我說的是資源的API調用),以及其他電話將不會被修改。

注:我一直在後臺技術如Java,星展銀行等。更長 時間,現在是第一次學習的角度,所以回答像 國防部:P,但這個想法是從我最後的Java項目。希望能幫助到你..!! :)