我正在关注this tutorial,目前我可以向用户登录和退出,但是当用户登录JWT令牌时,不会发送带有标头请求(我认为)所以我得到了401之后router.navigate
。当我重新加载页面时,我可以使用令牌,一切正常。
在我的login.component.ts中,我有这个登录功能:
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(result => {
if (result === true) {
// login successful
this.router.navigate(['home']);
} else {
// login failed
this.error = 'Username or password is incorrect';
this.loading = false;
}
}, error => {
this.loading = false;
this.error = error;
});
}
这将调用authentication.service.ts中的登录功能:
login(username: string, password: string): Observable<boolean> {
return this.http.post(this.authUrl, JSON.stringify({username: username, password: password}), {headers: this.headers})
.map((response: Response) => {
// login successful if there's a jwt token in the response
const token = response.json() && response.json().token;
if (token) {
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));
// return true to indicate successful login
alert('Success');
return true;
} else {
// return false to indicate failed login
alert('Fail');
return false;
}
}).catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
如果登录成功,用户将被路由到/ home:
this.router.navigate(['home']);
在home.component.ts中我有一个getAll函数返回数据库中的所有电影:
getAll() {
this._dataService
.getAll<Movie[]>()
.subscribe((data: any[]) => this.movies = data,
error => () => {
'something went wrong';
},
() => {
console.log(this.movies);
});
}
在ngOnInit:
上调用此函数ngOnInit(): void {
this.getAll();
}
在我的app.service.ts中,我有get函数:
public getAll<T>(): Observable<T[]> {
if (this.authenticationService.getToken()) {
console.log(this.authenticationService.getToken());
console.log(this.headers);
return this.http.get<T[]>('/api/movies/all', {headers: this.headers});
}
}
但是当我登录时,我在路由到主页后收到此错误:
获取http://localhost:4200/api/movies/all 401(未经授权)
问题(我认为)是当我被路由到主页时,标头缺少令牌。但是从控制台日志中可以看到,令牌在app.service.ts中可用。
当我重新加载页面时,我确实在标题中设置了令牌,一切正常:
有关如何在重定向后将令牌暴露给标头的任何想法?
// EDIT
出于某种原因,当我直接在函数中设置标题时,我确实得到了JWT标记:
return this.http.get<T[]>('/api/movies/all', {headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.authenticationService.getToken())});
而不是这样称呼它:
headers = new HttpHeaders().set('Authorization', 'Bearer ' + this.authenticationService.getToken());
return this.http.get('/api/movies/' + id, {headers: this.headers});