angular2通过服务刷新令牌

时间:2017-02-07 06:20:23

标签: angular authentication token access-token angular2-guards

在我的项目中,后端暴露了刷新令牌api。登录时,您将获得有效的令牌和刷新令牌。当令牌过期时,您需要进行刷新调用,并使用旧的过期令牌和参数刷新令牌进行授权。响应返回新的有效令牌和新的刷新令牌。目前我正试图在我的授权守卫中实施它。这是代码:

 import { Injectable } from '@angular/core';
 import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot }     from '@angular/router';
 import { Observable } from 'rxjs/Rx';

 import { SessionService } from '../services/session.service';

@Injectable()
export class AuthorizationGuard implements CanActivate {

constructor(private sessionService: SessionService, private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> {
    if (this.sessionService.isAuthenticated() ) {
        console.log('guard has cookies');
        return true;
    } else {
        if(this.sessionService.checkStorageSession() == null) {
            this.router.navigate(['/']);
        } else {
            console.log('guard will refresh token via refresh token call  ');
            this.sessionService.refreshToken()
                .subscribe(
                    data => {
                        console.log('guard  refresh success');
                        this.sessionService.destroySessionCookie();
                        this.sessionService.rememberUser(data.accessToken);
                        this.sessionService.rememberRefreshTocken(data.refreshToken);
                        this.sessionService.setSessionCookie(data.accessToken);
                        this.sessionService.setRefreshTocken(data.refreshToken);
                        return true;
                    },
                    error => {
                        console.log('session refresh fail: ' + error);
                        this.router.navigate(['/']);
                        return false;
                    }
            );
        }
    }
}

}

但是问题是canActivate调用,调用开始,刷新令牌,但是在刷新成功响应之前,我从激活页面上的其他调用中获得403未授权。此外,当我站在带有保存按钮的页面上时,我无法弄清楚如何刷新令牌,令牌过期,我按下保存并更新呼叫,但使用过期的令牌。请建议方法:s

1 个答案:

答案 0 :(得分:2)

我使用了这种方法,在AuthorizationGuard中你检查了:

if(!this.sessionService.isUserAuthenticated){
  this.router.navigate(['/']);
}

其中isAuthenticated = true表示用户具有有效的refreshToken。 我重写了http服务以获得刷新令牌逻辑:

var authenticatedCall: Observable<any>;
      if (needToken) {
          if (this.sessionService.isUserAuthenticated) {
               authenticatedCall = this.sessionService.acquireToken()
               .flatMap((token: string) => {
                         if (options1.headers == null) {
                           options1.headers = new Headers();
                         }
                            options1.headers.append('Authorization', 'Bearer ' + token);
                            return this.http.request(url, options1);
                     });
                }
                else {
                    authenticatedCall = Observable.throw(new Error("User Not Authenticated."));
                }
        }
        else {            
            authenticatedCall = this.http.request(url, options).map(this.extractData);
 }

作为示例,我使用了这个:https://github.com/sureshchahal/angular2-adal/blob/master/src/services/authHttp.service.ts