简体   繁体   English

通过服务angular2刷新令牌

[英]angular2 refresh token via service

In my project the backend exposed refresh token api. 在我的项目中,后端公开了刷新令牌api。 When you log in you get valid token and refresh token. 登录时,您将获得有效令牌并刷新令牌。 When the token expires you need to make a refresh call, authorized with the old expired token and parameter refresh token. 当令牌过期时,您需要进行刷新调用,并使用旧的过期令牌和参数刷新令牌进行授权。 The response returns new valid token and new refresh token. 响应返回新的有效令牌和新的刷新令牌。 At the moment i am trying to implement it inside my authorization guard. 目前,我正在尝试在我的授权保护中实施它。 This is the code: 这是代码:

 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;
                    }
            );
        }
    }
}

} }

But the problem is canActivate invokes, the call starts, refreshes token but i get 403 unauthorized from other calls that are on the activated page before the success response from the refresh. 但是问题是canActivate调用,调用开始,刷新令牌,但是在刷新成功响应之前,我从激活页面上的其他调用中获得403未经授权。 Also i cant figure out how to refresh token when i am standing on a page with save button, the token expires, i press save and update call is made, but with the expired token. 另外,当我站在带有“保存”按钮的页面上时,如果令牌过期,我按“保存”并进行更新调用,但令牌已过期,我无法弄清楚如何刷新令牌。 Please suggest approaches :s 请提出方法:

I used this approach, in AuthorizationGuard you have check of: 我使用了这种方法,在AuthorizationGuard中可以检查:

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

Where isAuthenticated=true means that user has valid refreshToken. 其中isAuthenticated = true表示用户具有有效的refreshToken。 And I overrided http service to have refresh token logic: 而且我重写了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);
 }

As example I used this: https://github.com/sureshchahal/angular2-adal/blob/master/src/services/authHttp.service.ts 例如,我使用了这个: https : //github.com/sureshchahal/angular2-adal/blob/master/src/services/authHttp.service.ts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM