当用户登录后,第二天它将保留缓存并显示已损坏的应用程序。令牌过期后,我们如何将用户重定向到登录页面?我们将JWT与基于Angular 6的离子3一起使用。这是代码:
Token service (provider)
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable()
export class TokenProvider {
constructor(private storage: Storage) { }
SetToken(token) {
return this.storage.set('auth-token', token);
}
async GetToken() {
return await this.storage.get('auth-token');
}
DeleteToken() {
this.storage.remove('auth-token');
}
async GetPayload() {
const token = await this.storage.get('auth-token');
let payload;
if (token) {
payload = token.split('.')[1];
payload = JSON.parse(window.atob(payload));
}
return payload.data;
}
}
拦截器
import { switchMap } from 'rxjs/operators';
import { TokenProvider } from './token/token';
import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from '@angular/common/http';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private tokenProvider: TokenProvider) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return fromPromise(this.tokenProvider.GetToken()).pipe(
switchMap(token => {
const headersConfig = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
if (token) {
headersConfig['Authorization'] = `beader ${token}`;
}
const _req = req.clone({ setHeaders: headersConfig });
return next.handle(_req);
})
);
}
}
应用程序组件:
this.storage.get('auth-token').then(token => {
if (token) {
this.tokenProvider.GetPayload().then(data => {
const params = {
room: 'global',
user: data.username
};
this.socket.emit('online', params);
});
this.nav.setRoot('TabsPage');
} else {
this.nav.setRoot('LoginPage');
}
});
});
}
但它似乎仍然无法正常工作。当令牌过期时,它仍然保持页面处于活动状态,而没有任何数据看起来像是被破坏的应用程序。我们如何解决此问题并将用户重定向到“登录”页面?
答案 0 :(得分:2)
两种处理令牌过期的方法,
import { switchMap } from 'rxjs/operators';
import { TokenProvider } from './token/token';
import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from '@angular/common/http';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private tokenProvider: TokenProvider) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return fromPromise(this.tokenProvider.GetToken()).pipe(
switchMap(token => {
const headersConfig = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
if (token) {
headersConfig['Authorization'] = `beader ${token}`;
}
const _req = req.clone({ setHeaders: headersConfig });
return next.handle(_req).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
// redirect to the login route
// or show a modal
}
}
});
})
);
}
}
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
答案 1 :(得分:0)
在这种情况下,请使用event。当登录请求由于令牌过期或凭证无效而出错时发布事件,并在app.component.ts上进行订阅,您可以在其中将登录页面设置为根页面。