Angular employs what it calls route guards for dealing with this sort of thing. (You will need to use the Angular Router to use guards.)
There are three types of guards: (1) CanActivate, (2) CanActivateChild, and (3) CanDeactivate. CanActivate is the primary guard used for authorization logic. Angular will call your guard before it tries to activate a route. If the guard returns true (or one of the async options Promise<boolean> or Observable<boolean>), the route can activate. Otherwise the route cannot not activate, and Angular will not navigate.
Example:
auth.guard.ts
export class AuthGuard implements CanActivate {
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return new Promise((resolve) => {
let isAuthorized = false;
// Call out to your authentication/authorization service.
resolve(isAuthorized);
});
}
}
app-routing.module.ts
const routes = [
{
// Any user can access this route
path: 'public'
}
{
// Only authorized users can access this route
path: 'secured',
canActivate: [AuthGuard]
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
providers: [
AuthGuard
]
})
export class AppRoutingModule {}
Do remember that you must always secure your application on the backend. Never implicitly trust any request from the frontend. Even though Angular is preventing routes from being activated, a shrewd hacker could get past that security mechanism. I recommend checking out JSON Web Tokens and a third provider auth provider. They are great way to integrate high-grade security into your stack. Auth0 offers a free tier of their identity-as-a-service platform.