I recently enabled Angular Universal in my project. Everything works as expected, except for one strange issue. Whenever I refresh page or click a link in email that navigates to webpage, I see Login page for brief second then actual page loads.
Sample project created and uploaded to Github. Remember the delay may not as long as in my real project.
Github repo link: https://github.com/pavankjadda/angular-ssr-docker
Problem:
As it turns out when Ng Express Engine loads the web page, it does not have access to cookies. Hence it redirects user to Login page, but as soon as browser loads JavaScript (Angular), which checks for cookies and validates Authentication guards, redirects user to actual webpage. The ideal solution would be making cookies available on server side (sending it through request) and making sure Authentication guards passes. I tried send the cookies through server.ts, but couldn't get it working.
Work Around:
Until I figure out the solution here is the work around I followed. Whenever we check for cookies, determine if the platform is server, if yes return true. Here are the few places where you can make this change
authservice.ts returns true when the platform is server /**
* Returns true if the 'isLoggedIn' cookie is 'true', otherwise returns false
*
* @author Pavan Kumar Jadda
* @since 1.0.0
*/
isUserLoggedIn(): boolean {
return isPlatformServer(this.platformId) || (this.cookieService.get('isLoggedIn') === 'true' && this.cookieService.check('X-Auth-Token'));
}
@Injectable({
providedIn: 'root'
})
export class CoreUserAuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router, @Inject(PLATFORM_ID) private platformId: any,) {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const url: string = state.url;
return this.checkLogin(url);
}
/**
* Returns true if the user is Logged In and has Core user role
*
* @author Pavan Kumar Jadda
* @since 1.0.0
*/
private checkLogin(url: string): boolean {
// Return if the platform is server
if (isPlatformServer(this.platformId))
return true;
if (this.authService.isUserLoggedIn() && this.authService.hasCoreUserRole()) {
return true;
}
if (this.authService.isUserLoggedIn() && !this.authService.hasCoreUserRole()) {
this.router.navigate(['/unauthorized']);
}
// Store the attempted URL for redirecting
this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
}
Note: Added work around here, in case if anyone has similar problem. When I have an actual solution to the problem, I will update this answer.
change your isUserLoggedIn() function in auth service to:
public async isUserLoggedIn(): Promise<boolean> {
const isLoggedIn = await this.cookieService.check("token");
return isLoggedIn;
}