2017-08-11 162 views
0

從Angular 4應用程序中,我調用部署在Tomcat上的REST服務。對於身份驗證,我使用的是Kerberos,並且正常情況下按預期工作。處理身份驗證錯誤

當Kerberos身份驗證失敗時(假設由於用戶不在AD中),我在處理Angular錯誤時遇到了一個問題。

這是我的角代碼

this.restService.executeGET(url) 
     .subscribe(
     (response: Response) => { 
     let httpResponseStatus = response.status; 
     console.log('httpResponseStatus: '+httpResponseStatus+', httpResponseAuthHeader: '+httpResponseAuthHeader) 
     //Do something with the Response 
     } 
     , 
     (error) => { 
     //Do something with the Error 
     console.log('Authenication Failed' + error); 

     } 
    ) 

executeGET(url: string) { 
    let reqHeaders = new Headers({ 'Content-Type': 'application/json' }); 
    reqHeaders.append('Accept', 'application/json'); 
    return this.http.get(url, { headers: reqHeaders }); 
    } 

當驗證成功和200由服務器返回, '(響應:響應)=> {}' 如預期被執行。當響應是帶有WWW-Authenticate:Negotiate標頭的401代碼時,'響應'塊和'錯誤'塊都不會被執行,並且瀏覽器顯示'頁面無法顯示'消息。

當我看看IE 11網絡標籤時,它顯示響應已經作爲401 /協商返回,但由於某種原因它迴避了角碼。

Response Header 1

Response Header 2

看來,瀏覽器顯示甚至在角碼有機會載入「網頁無法顯示」的消息。

即使身份驗證失敗,我如何確保某些代碼塊得到執行,以便我可以採取適當的措施將用戶重定向到登錄頁面。

+0

添加服務來處理類似'401'的錯誤,就像https://stackoverflow.com/questions/44108285/angular-4-custom-errorhandler-doesnt-r ecognize定製錯誤 –

回答

0

就在這個檢查添加到服務HTTP調用

import 'rxjs/add/operator/catch'; 
.catch(e => { 
      if (e.status === 401) { 
       return Observable.throw('Not authorized'); 
      } 
      // do other stuff 
     }); 

然後在組件訂閱

this.your service.methodname() 
     .subscribe(data => { 
      // your data 
     }, (err) => { 
      if (err === 'Not Authorized') { 
// Do your stuff here 
     }); 

如果你想在全球401處理器爲您的應用程序服務,您可以檢查這個答案是在Angular中使用http xhr Interceptor