I have developed a more organized approach for my application. My strategy involves categorizing pages into secured
and public
sections, using separate templates for each. By implementing public components
and secure components
, I can then apply the necessary guard
protection to the appropriate template.
It is crucial to include [Guard]
in the complete route requiring security measures.
When securing a route, I ensure to specify the parent routes in the app.routing.ts
file.
const APP_ROUTES: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full', },
{ path: '', component: PublicComponent, data: { title: 'Public Views' }, children: PUBLIC_ROUTES },
{ path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
];
export const routing = RouterModule.forRoot(APP_ROUTES);
Pay attention to this particular line,
{ path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
I establish two layouts:
/public/ for all public components
/public/public.routes.ts
/secure/ for all secure components
/secure/secure.routes.ts
Secure routes
Note that these specific routes do not require Guard
since their handling is managed by the template parent.
export const SECURE_ROUTES: Routes = [
{ path: '', redirectTo: 'overview', pathMatch: 'full' },
{ path: 'items', component: ItemsComponent },
{ path: 'overview', component: OverviewComponent },
{ path: 'profile', component: ProfileComponent },
];
Main routes in app.routing.ts
const APP_ROUTES: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full', },
{ path: '', component: PublicComponent, data: { title: 'Public Views' }, children: PUBLIC_ROUTES },
{ path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
];
export const routing = RouterModule.forRoot(APP_ROUTES);
Within the /layouts directory, I create the following layout structure:
/layouts/secure.component.ts
/layouts/secure.component.html
/layouts/public.component.ts
/layouts/public.component.html
All traffic flows through either the public
or secure
layout, with the [Guard]
reserved for secure routes only.
Moreover, I handle authentication utilizing a token stored locally.
@Injectable()
export class Guard implements CanActivate {
constructor(protected router: Router, protected auth: Auth ) {}
canActivate() {
if (localStorage.getItem('access_token')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page
this.router.navigate(['/home']);
return false;
}
}
Once I configure my setup as detailed above, I organize all secure routes under the secure directory and public routes under the public directory. Route definitions are written in the respective public.routes.ts or secure.routes.ts file within their designated folder.