Context :
After following multiple tutorials, I have been experimenting with authentication in Angular2 using JWT. I have created a component and a service named:
app.component.ts
user.service.ts
The app component (along with its template) contains a subscription to an observable that displays the user's logged-in status. The Observable item is stored in the user service and updates correctly when the user logs in or out.
The authentication token is stored in "localStorage" as "auth_token," which includes a time-based validity value that requires the user to log in again after a certain period.
My goal is to VERIFY the token validity upon app initialization. Initially, I attempted to do this in the user.service constructor without success. Then, I tried in the ngOnInit of the app.component, followed by an event call from the app component (button click), but encountered failures each time!
Some code snippets :
//app.component.html
//...
<a md-button class="app-icon-button" aria-label="checklogin" (click)="checkLogin()">
<md-icon svgIcon="check"></md-icon>
</a>
//...
//app.component.ts
//...
checkLogin(){
console.log('CHECK LOGIN FUNCTION');
let token = localStorage.getItem('auth_token');
if(token){
console.log('TOKEN FOUND');
this.userService.checkToken(token);
}else{
console.log('NO TOKEN FOUND');
}
}
//...
//user.service.ts
//...
checkToken(token){
console.log('CHECK TOKEN FUNCTION');
console.log('TOKEN : '+token);
let headers = new Headers();
headers.append('Content-Type','application/json');
return this.http
.post(
'/url/script.php',
JSON.stringify(token),
{ headers }
)
.map(res => res.json())
.map((res) => {
console.log('SCRIPT RESULT : ');
if(res.valid){
console.log('TOKEN IS VALID');
return true;
}else{
console.log('TOKEN NOT VALID');
return false;
}
});
}
//...
I have omitted the part about observables and subscriptions.
Problem :
The main issue is that the app NEVER CALLS the script!
Whenever I click on the "checkLogin" button (with a valid token),
Console displays 'CHECK LOGIN FUNCTION',
Console displays 'TOKEN FOUND',
Console displays 'CHECK TOKEN FUNCTION',
Console displays 'TOKEN : '****************************** (token),
However, it never shows 'SCRIPT RESULT', and upon checking with Firebug for the HTTP calls, there seems to be NO CALL to the script.php. It appears that the this.http part is being ignored...
Thank you for reading/help