最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Angular Guard doesn't work when reloading page (v19) - Stack Overflow

programmeradmin4浏览0评论

Recently I have been through some trouble with my auth guard, which calls the API to check if current user is successfully logged in sending the auth cookie. This API returns a boolean value.

The guard works perfect when trying to access /dashboard without previously logging in, however, when I'm already navigating through the /dashboard routes, and refresh the page it asks me to login again.

I realised that when this happens, guard isn't calling backend to check the auth. Is anyone else having the same problem?

PD: SSR is enabled on my project

{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard], children: [ // children routes ] }

Guard:

export const authGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);

  return authService.checkAuth().pipe(
    map(isAuthenticated => {
      if (!isAuthenticated) {
        router.navigate(['/login']);
        return false;
      }
      return true;
    }),
    catchError(error => {
      console.error(error);
      router.navigate(['/login']);
      return of(false);
    })
  );
};

Check auth method:

checkAuth():Observable<Boolean> {
    return this.http.get<Boolean>(`${this.apiUrl}/api/v1/auth/check-auth`, {withCredentials: true}).pipe(
      catchError(this.handleError)
    );
  }

I have already tried using CanActivateChild instead of CanActivate to see if the trouble is related to the children routers, but stil doesn't work and to be honest I'm new to Angular so I don't know what else to try...

I could've tried to use localStorage to store a value after user is logged in, but SSR is enabled on my project.

Recently I have been through some trouble with my auth guard, which calls the API to check if current user is successfully logged in sending the auth cookie. This API returns a boolean value.

The guard works perfect when trying to access /dashboard without previously logging in, however, when I'm already navigating through the /dashboard routes, and refresh the page it asks me to login again.

I realised that when this happens, guard isn't calling backend to check the auth. Is anyone else having the same problem?

PD: SSR is enabled on my project

{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard], children: [ // children routes ] }

Guard:

export const authGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);

  return authService.checkAuth().pipe(
    map(isAuthenticated => {
      if (!isAuthenticated) {
        router.navigate(['/login']);
        return false;
      }
      return true;
    }),
    catchError(error => {
      console.error(error);
      router.navigate(['/login']);
      return of(false);
    })
  );
};

Check auth method:

checkAuth():Observable<Boolean> {
    return this.http.get<Boolean>(`${this.apiUrl}/api/v1/auth/check-auth`, {withCredentials: true}).pipe(
      catchError(this.handleError)
    );
  }

I have already tried using CanActivateChild instead of CanActivate to see if the trouble is related to the children routers, but stil doesn't work and to be honest I'm new to Angular so I don't know what else to try...

I could've tried to use localStorage to store a value after user is logged in, but SSR is enabled on my project.

Share Improve this question asked 6 hours ago Carlos Esteban CastroCarlos Esteban Castro 111 bronze badge New contributor Carlos Esteban Castro is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

1 Answer 1

Reset to default 0

You can also explore Hybrid Rendering with SSR routes to conditionally render these routes with a guard.

// app.routes.server.ts
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
  {
    path: '/protected-route', // This renders the "/protected-route" route on the client (CSR)
    renderMode: RenderMode.Client,
    canActivate: [authGuard],
  },

When SSR is enabled, by default deny permissions to the page, so that it is only evaluated on the browser for this we use isPlatformBrowser(platformId).

export const authGuard: CanActivateFn = (route, state) => {
  const platformId = inject(PLATFORM_ID);
  const authService = inject(AuthService);
  const router = inject(Router);
  if (isPlatformBrowser(platformId)) {
    return false;
  }
  return authService.checkAuth().pipe(
    map(isAuthenticated => {
      if (!isAuthenticated) {
        router.navigate(['/login']);
        return false;
      }
      return true;
    }),
    catchError(error => {
      console.error(error);
      router.navigate(['/login']);
      return of(false);
    })
  );
};
发布评论

评论列表(0)

  1. 暂无评论