I’m currently developing an Angular application which has a protected page. I’m protecting the page by using a custom guard:
{
path : 'intern', // For testing purposes (internal page)
component : InternalComponent,
canActivate: [loggedInGuard],
}
This is my login guard:
export const loggedInGuard: CanActivateFn = (route, state): Promise<boolean> => {
const loginService = inject(LoginService);
const router = inject(Router);
return new Promise((resolve, reject) => {
loginService.isLoggedIn().then((isLoggedIn) => {
if (!isLoggedIn) {
router.navigate(['/anmelden'], {queryParams: {redirect_to: state.url}}).then(() => {
resolve(false);
});
} else {
resolve(true);
}
});
});
};
Inside the guard, I need to check if the user is logged in using my service:
public async isLoggedIn(): Promise<boolean> {
const token = localStorage.getItem(this.tokenKey);
if (!token) {
return false;
}
try {
// await axios.post(this.verifyLoginUri, {token});
return true;
} catch (error) {
this.logout();
return false;
}
}
First, I check if the token returned and set during login is still set inside the local storage. If yes, I use the token to make a backend request using axios to check if the token in still inside my Redis DB. If no, I return a 401 error, which is processed by the catch block. If it’s still inside the DB, I return 200.
The thing is that somehow my guard seems to ignore the request to the backend totally. When I comment in the axios request again, the protected page has no content. If I comment it out, the content is there depending on the local storage entry.
What am I doing wrong here? I mean, this is a logic use case. Every service validates the session inside the backend. Otherwise, some smart guy can just set the local storage entry and enjoy the internal page.