处理身份验证错误
问题描述:
从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 /协商返回,但由于某种原因它回避了角码。
看来,浏览器显示甚至在角码有机会载入“网页无法显示”的消息。
即使身份验证失败,我如何确保某些代码块得到执行,以便我可以采取适当的措施将用户重定向到登录页面。
答
就在这个检查添加到服务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
添加服务来处理类似'401'的错误,就像https://stackoverflow.com/questions/44108285/angular-4-custom-errorhandler-doesnt-r ecognize定制错误 –