【发布时间】:2017-03-08 15:45:55
【问题描述】:
所以我有一个简单的 Angular 2/laravel 应用程序,它支持 jwt 身份验证。我有一个服务,每次调用路由时都会使用 angular2-jwt tokenNotExpired() 函数验证 jwt 令牌是否有效,但此函数总是出于某种原因返回 false,因此用户将始终被重定向到登录页面。
因此,就像用户登录一样,将从后端生成一个令牌并保存在本地存储中,然后服务将在使用 CanActivate 生命周期挂钩启动任何路由之前检查令牌是否有效。
这是我到目前为止所做的:
登录组件:
...
this.http.post(SERVER_URL + 'auth', body, {
headers: headers
}
).subscribe(
data => {
localStorage.setItem('auth_token', data.json().token);
this.authHttp.get(SERVER_URL + 'auth/user', headers)
.subscribe(
data => {
this.store.dispatch({ type: SET_CURRENT_USER_PROFILE, payload: data.json().user });
localStorage.setItem('user', data.json().user);
this.router.navigate(['/home']);
},
err => console.log('Fehlermeldung: ' + err)
);
},
...
应用程序模块:
...
{ provide: AuthConfig, useValue: new AuthConfig({
headerName: 'Authorization',
headerPrefix: 'Bearer ',
tokenName: 'auth_token',
tokenGetter: (() => localStorage.getItem('auth_token')),
globalHeaders: [{ 'Content-Type': 'application/json' }],
noJwtError: true,
noTokenScheme: true
})},
AuthHttp
...
auth.service: // 检查 JWT 令牌服务
import { tokenNotExpired } from 'angular2-jwt';
import { Injectable } from '@angular/core';
@Injectable()
export class AuthService {
loggedIn() {
return tokenNotExpired();
}
}
auth.guard.service:
// Check if the Token of the user is still valid
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
import { AppState } from '../shared/interfaces';
import { SET_CURRENT_USER_PROFILE } from '../shared/state.actions';
import { Store } from '@ngrx/store'
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private auth: AuthService, private router: Router, private store: Store<AppState>) {}
canActivate() {
if(this.auth.loggedIn()) {
return true;
} else {
console.log ('Token expired or not valid')
localStorage.setItem('auth_token', '');
localStorage.setItem('user', '');
this.store.dispatch({ type: SET_CURRENT_USER_PROFILE, payload: null });
this.router.navigate(['/']);
return false;
}
}
}
应用程序路由:
const routes: Routes = [
{ path: 'home', component: HomeComponent},
{ path: 'about', component: AboutComponent, canActivate: [AuthGuardService]},
{ path: 'profile/:id', component: ProfileComponent, canActivate: [AuthGuardService]},
{ path: '', component: LoginComponent}
];
编辑:从后端来看,一切正常,因为令牌是在用户登录后生成并存储在本地存储中的。
【问题讨论】: