【问题标题】:Handling authentication errors in response在响应中处理身份验证错误
【发布时间】:2017-08-11 10:08:37
【问题描述】:

从 Angular 4 应用程序中,我正在调用部署在 Tomcat 上的 REST 服务。对于身份验证,我使用的是 Kerberos,它在积极的情况下按预期工作。

当 Kerberos 身份验证失败时(假设由于 AD 中不存在用户),我在处理 Angular 中的错误时遇到了问题。

这是我的 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 });  
  }   

当 Authentication 成功并且服务器返回 200 时,'(response: Response) => {}' 会按预期执行。当响应是带有 WWW-Authenticate: Negotiate 标头的 401 代码时,“响应”块和“错误”块都不会被执行,并且浏览器会显示“无法显示页面”消息。

当我查看 IE 11 网络选项卡时,它显示响应已作为 401/Negotiate 返回,但由于某种原因它正在逃避角码。

似乎浏览器在 Angular 代码有机会加载之前就显示“无法显示页面”消息。

如何确保即使身份验证失败也能执行某些代码块,以便我可以采取适当的措施,例如将用户重定向到登录页面。

【问题讨论】:

标签: angular rest authentication kerberos http-authentication


【解决方案1】:

只需将此检查添加到服务 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 Interceptor 中使用 http xhr 的答案

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 2021-07-11
    • 1970-01-01
    • 2023-04-10
    • 2018-09-13
    • 2016-06-12
    • 2018-11-04
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多