I'm using a RxJs Subject
authListener
to get user auth status:
export class AuthService {
private authListener = new Subject<boolean>();
isLoggedIn() { return this.authListener.asObservable(); }
login() {
localStorage.setItem('token', token);
...
this.authListener.next(true);
}
logoff() {
localStorage.removeItem('token');
...
this.authListener.next(false);
}
}
So i'm able to call authListener
value in components:
export class HeaderComponent implements OnInit {
isAuthenticated = false;
auth$: Subscription;
constructor(private authService: AuthService) { }
ngOnInit() {
this.auth$ = this.authService.isLoggedIn().subscribe(
(isAuth: boolean) => {
this.isAuthenticated = isAuth;
});
}
}
However it doesn't seem reliable because the user could do something like refreshing the page, and then authListener
would be lost. Is there a reliable way to do it?
I'm trying to avoid localStorage because user could change authListener anytime.
UPDATE: It seems storing cookies is the way to go. How could I store Auth State
and JWT Token
inside a cookie using Node.js + Express (HttpOnly; Secure)?
It should be something like this...
// login original response
res.status(200).json({success: true, token: token, reftoken: refreshToken, expiresIn: 900, name: user.name});
// login cookie response
res.cookie('token', token, { secure: true, httpOnly: true });
res.cookie('tokenref', refreshToken, { secure: true, httpOnly: true });
res.cookie('expiration', expireDate, { secure: true, httpOnly: true });
res.status(200).json({success: true, name: user.name});