Angular App with authentication that serves files only after login
In my precedent work that was the flow:Node was serving all the files after login.
Simply check if token is valid (token in the header), if it is allow access to the index.html otherwise redirect user to a login page.
Don't include the login page to the angular app. It can be a simple html file with an ajax call (jQuery) in order to send the credentials.If credentials are OK, on the success response redirect user to the index.html including token in headers for authentication
To protect your module in an Angular app from even loading into browser, you should use canLoad
guard like this:
path: 'customers',canLoad: [AuthGuard],loadChildren: 'app/customers/customers.module#CustomersModule'
where CustomersModule
is NgModule including all components you want to 'hide'. The code for this module will be separated in a chunk file and will only be loaded if the AuthGuard.canLoad
returns true
.
You can have a look at this simple app https://solid-flow.github.io/secure-app/customers and see in the dev console how different parts of the source code are loaded. The github repo can be found here https://github.com/solid-flow/secure-app
With AngularCLI
Use WebPack to zip code
ng build --prod
Use Routing config with simple AuthGuard implementation for unwanted access
{ path: '', redirectTo: 'home', pathMatch: 'full',},{ path: 'private', component: FullLayoutComponent, canActivate: [AuthGuard] // just auth users access}
AuthGuard.ts
import { Injectable } from '@angular/core';import { Router, CanActivate } from '@angular/router';@Injectable()export class AuthGuard implements CanActivate { constructor(private router: Router) { } canActivate() { if (localStorage.getItem('TOKEN')) { return true; } // not logged in so redirect to login page this.router.navigate('login'); return false; }}