Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
how to use AuthGuard correctly

I have an angular application where I want to use authguard to protect some routes but for some reason it does not work. I first make a post request to my spring boot backend, if that gives me success I set a value to true and check that value in my canActivate methode. But it does not work, it does not even go into that method. I thought it is called automatically if I set it in my path in app-route.module. How can I use it correctly?

Authenticationservice with authguard together:

export class AuthenticationService {




  constructor(
    private http: HttpClient,
    private router: Router,

  ) { }

  authenticateUser(login: LoginModel){
    return this.http.post(environment.rootUrl + 'authenticate', {
      username: login.username,
      password: login.password,
    }).subscribe({
      next: (data) => {
       localStorage.setItem('token', data.toString())
      }, error: (error) => {
        this.isAuthenticated = false
      }
    })
  }

  isUserLoggedIn(){
    return !!localStorage.getItem('token')
  }

  
}

Authguard:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(
    private auth: AuthenticationService,
    private router: Router
  ) {
  }

  canActivate(): Promise<boolean> {
    return new Promise(resolve => {
      if (this.auth.isUserLoggedIn()) {
        resolve(true)
      } else {
        this.router.navigate(['authenticate'])
        resolve(false)
      }
    })
  }
}

App-module:

@NgModule({
  declarations: [AppComponent, NxWelcomeComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    NbLayoutModule,
    LoginComponentModule,
    AppRoutingModule,
    NbThemeModule.forRoot({ name: 'default' }),
    NbLayoutModule,
    NbEvaIconsModule,
  ],
  providers: [AuthGuard],
  bootstrap: [AppComponent],
})
export class AppModule {}

App-routing-module:

const routes: Routes = [
  {path: 'dashboard' , component: DashboardComponent, canActivate: [AuthGuard]},
  {path: 'authenticate', component: LoginComponent},
  {path: '' , redirectTo: 'authenticate', pathMatch: 'full'}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [AuthGuard]
})
export class AppRoutingModule {

}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You need to route to the dashboard after you do the login:

The routes:

const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard],
  },
  { path: '', redirectTo: 'authenticate', pathMatch: 'full' },
];

The Component:

export class AppComponent {
  constructor(
    private authService: AuthenticationService,
    private router: Router
  ) {}

  callServiceMethod(value: string) {
    // This will need to wait for auth to finish before navigating in the actual app.
    this.authService.authenticateUser(value);
    if (this.authService.isAuthenticated) {
      this.router.navigate(['dashboard']);
    }
  }
}

The Guard:

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthenticationService, private router: Router) {}

  canActivate(): Promise<boolean> {
    return new Promise((resolve) => {
      console.log('running auth guard!');
      if (this.auth.isUserLoggedIn()) {
        resolve(true);
      } else {
        this.router.navigate(['authenticate']);
        resolve(false);
      }
    });
  }
}

Here is an updated example:

https://stackblitz.com/edit/angular-ivy-5excpc?file=src%2Fapp%2Fapp.component.ts

about 4 years ago · Juan Pablo Isaza Denunciar

0

Your canActivate should only take your AuthGuard class which has the resolver.

{path: 'dashboard' , component: DashboardComponent, canActivate: [AuthGuard]}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda