如何通过刷新令牌更新访问令牌?

时间:2019-11-12 22:55:55

标签: javascript angular typescript ionic-framework jwt

登录时,我会重新获得访问权限并刷新令牌。当第一个访问令牌过期时,我想将刷新令牌发布到api,以便在刷新令牌有效时获取新的访问令牌。我设法建立了访问令牌请求。因此,我通过身份验证的时间大约为5分钟,但我未通过身份验证。不再。因此,我尝试发出发帖请求{refresh}以获得新的访问令牌,但不知何故,我仍然在5分钟后被踢出局。 对于this.user日志,我得到以下数据:

exp: 1573685426
jti: "5897b0c9"
token_type: "refresh"
user_id: 1

这是我尝试过的:

app.module.ts

export function jwtOptionsFactory(storage) {
  return {
    tokenGetter: () => {
      return storage.get('access_token');
    },
    refreshGetter: () => {
      return storage.get('refresh_token');
    },
    whitelistedDomains: ['localhost']
  };

}

...

  imports: [BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule, 
    HttpClientModule,
    DeviceDetectorModule.forRoot(),
    IonicStorageModule.forRoot(),
    JwtModule.forRoot({
      jwtOptionsProvider: {
        provide: JWT_OPTIONS,
        useFactory: jwtOptionsFactory,
        deps: [Storage]
       }
    }) ]

auth.service.ts

import { Storage } from '@ionic/storage';
import { JwtHelperService } from '@auth0/angular-jwt';

export const TOKEN_KEY = 'access_token';
export const REFRESH_TOKEN_KEY = 'refresh_token';
...
  constructor(private http: HttpClient, private storage: Storage, private helper: JwtHelperService,
              private plt: Platform) {
    this.plt.ready().then(() => {
      this.checkToken();
    });
   }

   checkToken() {
       this.storage.get(TOKEN_KEY).then(access => {
           if (access) {
               this.user = this.helper.decodeToken(access);
               this.authenticationState.next(true);
           }
       });
   }

   checkRefreshToken() {  // don't know if needed
    this.storage.get(REFRESH_TOKEN_KEY).then(refresh => {
        if (refresh) {
            this.user = this.helper.decodeToken(refresh);
            this.authenticationState.next(true);
        }
    });
}

   apilogin(username: string, password: string) {
    return this.http.post<any>(`${this.url}/api/token/`, { username, password })
    .pipe(
        tap(res => {
            this.storage.set(TOKEN_KEY, res['access']);
            this.storage.set(REFRESH_TOKEN_KEY, res['refresh']);
            this.user = this.helper.decodeToken(res['access']);
            this.user = this.helper.decodeToken(res['refresh']);
            console.log('my user: ', this.user);
            this.authenticationState.next(true);
        }),
   );
}

getRefresh(refresh: string) { // post the refresh token to get a new access
    return this.http.post<any>(`${this.url}/api/token/refresh/`, {refresh})
    .pipe(
        tap(res => {
            this.storage.set(REFRESH_TOKEN_KEY, res['refresh']);
            this.user = this.helper.decodeToken(res['refresh']);
        })
    );
}

0 个答案:

没有答案