User.js (backend)
//profile
router.get('/profile', passport.authenticate('jwt', { session: false }), (req, res) => {
res.json({
user: req.user,
})
});
Angular
Login Component:
//onLoginSubmit() is a event Based function
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']);
}
});
}
On success The return of the data of subscribe is an object:
success:true
token:"bearer aGh..........Q2rEjhnZ6XjXVKmwNFoiWFjEJk"
Then if i am accessing the private Route e.g(profile) than it is unauthorizing it
Profile Component
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;
})
}
}
The AuthService(Injected to all)
_/**
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 Repository link
While i am accessing the protected Route the error is :
Http failure response for http://localhost:8080/users/profile: 401 Unauthorized