Authentication verifies submitted credentials before exposing administration features. A login form sends a username and password to a RESTful web service, which returns success or failure. section 7.1.1 section 7.2
A token-based Angular implementation follows this sequence:
- Post the credentials to /login as JSON containing name and password properties. section 7.2.1
- Receive a JSON Web Token when authentication succeeds; send it with later requests in the Authorization header as a Bearer token. section 7.2.1
- Encapsulate authentication behind AuthService, expose an authenticated state, and clear the stored token when needed. section 7.2.3
- Use an Angular route guard to redirect unauthenticated users to the login route before protected administration requests occur. section 7.2.4
SportsStore administration login
The form requires both username and password. Valid credentials navigate to /admin/main; invalid credentials display an error. The demonstration service accepts admin and secret, while its JWT expires after one hour and is not stored persistently. section 7.2.1 section 7.2.4
Listing 7.12. The contents of the auth.guard.ts file in the src/app/admin folder
import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, RouterStateSnapshot,
Router } from "@angular/router";
import { AuthService } from "../model/auth.service";
@Injectable()
export class AuthGuard {
constructor(private router: Router,
private auth: AuthService) { }
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (!this.auth.authenticated) {
this.router.navigateByUrl("/admin/auth");
return false;
}
return true;
}
}
Inspect the AuthGuard implementation that checks authentication state, redirects to /admin/auth, and denies protected navigation. section 7.2.4

































