Angular2 - How to best handle expired authentication token?

前端 未结 5 1273
孤独总比滥情好
孤独总比滥情好 2021-02-05 11:06

I am using Angular 2.1.2.

I have an authentication token (using angular2-jwt) and if it expires my webApi call fails with a 401 error. I am looking for a solution where

5条回答
  •  广开言路
    2021-02-05 11:26

    Usually I would provide a HttpService myself instead of using Http directly. So with your requirement, I can provide my own get() method to chain the authentication before sending any real HTTP requests.

    Here is the service:

    @Injectable()
    class HttpService {
      constructor(private http: Http, private auth: Authentication) {}
    
      public get(url: string): Observable {
        return this.auth.authenticate().flatMap(authenticated => {
          if (authenticated) {
            return this.http.get(url);
          }
          else {
            return Observable.throw('Unable to re-authenticate');
          }
        });
      }
    }
    

    Here is the component to call the service:

    @Component({
      selector: 'my-app',
      template: `

    Hello {{name}}

    Do you confirm to log in?

    `, }) export class AppComponent { name = 'Angular'; constructor(private httpSvc: HttpService, public auth: Authentication) {} ngOnInit() { } doSomething() { let a = this.httpSvc.get('hello.json').subscribe(() => { alert('Data retrieved!'); }, err => { alert(err); }); } yes() { this.auth.confirm.emit(true); } no() { this.auth.confirm.emit(false); } }

    By chaining observables, the Authentication service determines whether to interrupt the normal flow to show the modal (though currently only lives with the App component, it can certainly be implemented separately). And once a positive answer is received from the dialog, the service can resume the flow.

    class Authentication {
      public needsAuthentication = true;
      public showModal = false;
      public confirm = new EventEmitter();
    
      public authenticate(): Observable {
        // do something to make sure authentication token works correctly
        if (this.needsAuthentication) {
          this.showModal = true;
          return Observable.create(observer => {
            this.confirm.subscribe(r => {
              this.showModal = false;
              this.needsAuthentication = !r; 
              observer.next(r);
              observer.complete();
            });
          });
        }
        else {
          return Observable.of(true);
        }
      }
    }
    

    I have a full live example here.

    http://plnkr.co/edit/C129guNJvri5hbGZGsHp?open=app%2Fapp.component.ts&p=preview

提交回复
热议问题