代码之家  ›  专栏  ›  技术社区  ›  kayasa

在响应中处理身份验证错误

  •  0
  • kayasa  · 技术社区  · 8 年前

    从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时,“(响应:response)=>{}按预期执行。当响应为401代码且WWW Authenticate:Negotiate标头时,“响应”块和“错误”块均未执行,浏览器显示“页面无法显示”消息。

    Response Header 1

    Response Header 2

    甚至在角度代码加载之前,浏览器似乎就显示了“页面无法显示”消息。

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

    1 回复  |  直到 8 年前
        1
  •  1
  •   Rahul Singh    8 年前

    只需将此检查添加到服务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