User.js (后端)
//个人资料
router.get('/profile', passport.authenticate('jwt', { session: false }), (req, res) => {
res.json({
user: req.user,
})
});
角度
登录组件:
// onLoginSubmit()是基于事件的函数
onLoginSubmit(){
const user ={
username:this.username,
password:this.password
}
this._authService.authenticateUser(user).subscribe(data=>{
console.log(data);
this._dataServiceData=data;
if(this._dataServiceData.success){
this._authService.storeUserData(this._dataServiceData.token,this._dataServiceData.user);
this._flahMessage.show('You are now Logged in !',{cssClass:'alert-success',timeout:3000});
this._router.navigate(['dashboard']);
}else{
this._flahMessage.show(this._dataServiceData.msg,{cssClass:'alert-danger',timeout:3000});
this._router.navigate(['login']);
}
});
}
成功后,订阅数据的返回是一个对象:
成功:true
令牌:“ bearer aGh .......... Q2rEjhnZ6XjXVKmwNFoiWFjEJk”
然后,如果我正在访问私有路线(例如,配置文件)而不是未授权
个人资料组件
export class ProfileComponent implements OnInit {
private _dataService:any={};
public user={};
constructor(private _authService:AuthService,
private _router:Router) { }
ngOnInit() {
this._authService.getProfile().subscribe(data=>{
console.log(data);
this._dataService=data;
this.user = this._dataService.user;
},err=>{
console.log(err);
return false;
})
}
}
AuthService (已全部注入)
_ / **
authenticateUser(user){ **called from loginComponent**
let headers = new HttpHeaders();
headers.append('content-type','application/json');
return this.http.post('http://localhost:8080/users/authenticate',user,{headers:headers})
}
getProfile(){ **called from profileComponent**
let headers = new HttpHeaders();
this.loadToken();
headers.append('Authorization',this.token);
headers.append('content-type','application/json');
return this.http.get('http://localhost:8080/users/profile',{headers:headers})
}
loadToken(){
const token = localStorage.getItem('id_token');
this.token=token;
}
storeUserData(token,user){
localStorage.setItem('id_token',token);
localStorage.setItem('user',JSON.stringify(user));
this.token = token;
this.user=user;
}
GitHub存储库link
我正在访问受保护的路由时,错误是:
http://localhost:8080/users/profile的Http错误响应:401未经授权