【发布时间】:2019-12-07 18:01:44
【问题描述】:
我尝试在 Angular 7 中使用路由实现标准 JWT 授权。我的 app-routing.module.ts 的一部分:
{
path: '',
component: MainComponent,
canActivate: [AuthGuard]
},
{
path: '401',
component: UnauthorizeComponent
}
我也有 auth.service.ts:
const helper = new JwtHelperService();
const myRawToken = localStorage.getItem('token');
const isExpired = helper.isTokenExpired(myRawToken);
@Injectable()
export class AuthService {
...
public isAuthenticated(): boolean {
return !isExpired;
还有 - auth-guard.service.ts:
@Injectable()
export class AuthGuardService implements CanActivate {
...
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['401']);
return false;
}
return true;
}
}
在 Header 组件中,我有带有“登录”项的下拉列表,我的代码有:
sendLogin() {
const body = new HttpParams()
.set('username', this.loginForm.value.login)
.set('password', this.loginForm.value.password);
this.authService.login(body.toString())
.pipe(
catchError(err => {
return ......;
}))
.pipe(
tap(resp => {
localStorage.setItem('token', resp.headers.get('Authorization'));
this.router.navigate(['']);
}))
.subscribe();
}
所以,它工作正常,但我的标题组件中的 this.router.navigate(['']) 不起作用。而不是 '' url 浏览器打开 this.router.navigate(['401']); 因为 helper.isTokenExpired(myRawToken) 无法刷新令牌。但是,如果我在浏览器中按 F5(刷新)并转到 localhost:4200/ - 我的页面将打开。
我做错了什么?
如何刷新令牌?
【问题讨论】: