I am in the process of developing an Angular application that includes a protected page. To secure this page, I have implemented a custom guard:
{
path : 'intern', // For testing purposes (internal page)
component : InternalComponent,
canActivate: [loggedInGuard],
}
The code for my login guard is as follows:
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(['/login'], {queryParams: {redirect_to: state.url}}).then(() => {
resolve(false);
});
} else {
resolve(true);
}
});
});
};
Within the guard, it is essential to check if the user is logged in using the service provided:
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;
}
}
Initially, a check is made to ensure that the token received during login is still saved in local storage. If present, the token is used to make a backend request utilizing axios to confirm its existence within the Redis DB. In case the token cannot be found, a 401 error is returned and handled by the catch block. If the token does exist in the database, a 200 response is sent back.
However, it seems that the guard is not processing the backend request correctly. When the axios request is enabled, the protected page displays no content. On the other hand, when the request is disabled, the content on the page appears based on the local storage data.
I am puzzled about what mistake I might be making. This scenario aligns with common security practices where every service validates sessions in the backend to prevent unauthorized access through manipulation of local storage data.