Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular routing to always go to login page if user is not logged in

Tags:

angular

I would like to setup my Angular routes to do the following:

Landing page of website (http://localhost:4200) and any other routes should go to the LoginComponent if user is not logged in.

Landing page of website (http://localhost:4200) and any unmatched routes should go to the DashboardComponent if user is logged in. If route is matched should go to correct Component.

All matched routes should be protected by the AuthGuard which checks if the user is logged in. If user is not logged in they should end up on LoginComponent. (AuthGuard handles this redirect).

One major issue that I am facing is that I do not want the LoginComponent to be part of my app.component structure which has a router outlet in it (i.e. header, footer, sidebar). Instead I just want the login page to only display what is in LoginComponent.html.

Here are my current routes:

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', redirectTo: '/dashboard', pathMatch: 'full', canActivate: [AuthGuard] },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'projects', component: ProjectListComponent, canActivate: [AuthGuard] },
  { path: 'projects/new', component: ProjectDetailComponent, canActivate: [AuthGuard] },
  { path: 'projects/edit/:id', component: ProjectDetailComponent, canActivate: [AuthGuard] }
];
like image 456
Blake Rivell Avatar asked Jan 02 '23 00:01

Blake Rivell


1 Answers

One problem with the AuthGuard approach is that you could pass the AuthGuard and then your session at the backend expires. However, you will not get kicked out until you change route.

To overcome this people generally use an HTTP interceptor. An interceptor basically kicks you out if any HTTP request responds with 401 Unauthorised by redirecting to the login page (unless you are already on the login page).

This way, if the user does not change route and starts clicking about and the backend responds 401, the user is kicked out even if they do not change route.

Whilst this does not answer your question it is highly relevant.

Hope it helps.

like image 91
danday74 Avatar answered Jan 16 '23 12:01

danday74