Angular Authentication
Authentication proves who a visitor is. A login page, a protected dashboard, and a Logout button all belong to this topic. Most real applications need it, because they show private data such as orders, grades, or messages. We build a token-based login flow with the pieces you already know: services, guards, and interceptors.
The Event Ticket Idea
Think of a concert. You show your ID at the gate once and receive a wristband. Inside the venue, staff only look at the wristband. They never ask for your ID again. A token works like that wristband. The visitor logs in once, receives a token, and sends the token with every later request.
1. Visitor sends email + password
|
v
+-----------+
| Server | checks the details
+-----------+
|
2. Server returns a token
|
v
3. App stores the token
|
v
4. Every request carries the token --> Server accepts it
The Main Parts
| Part | Job |
|---|---|
| Login component | Collects the email and password |
| Auth service | Calls the server and stores the token |
| Interceptor | Adds the token to each request |
| Guard | Blocks private pages for visitors who are not logged in |
Step 1: Build the Auth Service
The service sends the login request and keeps track of the login state in a signal.
import { Injectable, inject, signal, computed } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { tap } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class AuthService {
private http = inject(HttpClient);
private token = signal<string | null>(null);
isLoggedIn = computed(() => this.token() !== null);
login(email: string, password: string) {
return this.http.post<{ token: string }>('/api/login', { email, password })
.pipe(tap(response => this.token.set(response.token)));
}
logout() {
this.token.set(null);
}
getToken() {
return this.token();
}
}The service keeps the token in memory. A page refresh clears it, which is the safest option for beginners. Production applications often rely on secure cookies set by the server so that refreshes keep the visitor logged in.
Step 2: Build the Login Form
login() {
const { email, password } = this.form.getRawValue();
this.auth.login(email, password).subscribe({
next: () => this.router.navigate(['/dashboard']),
error: () => this.message.set('Email or password is incorrect.')
});
}The message avoids saying which part was wrong. A vague message gives attackers less information.
Step 3: Attach the Token
The interceptor reads the token from the service and adds it to every outgoing request.
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).getToken();
if (!token) return next(req);
return next(req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
}));
};Step 4: Protect Pages with a Guard
The guard checks the login state before it opens a route. Visitors without a token move to the login page.
import { CanActivateFn, Router } from '@angular/router';
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isLoggedIn() ? true : router.createUrlTree(['/login']);
};
// route
{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] }Show Different Menus
The login signal helps the template adapt. A logged-in visitor sees a Logout button, and a guest sees a Login link.
@if (auth.isLoggedIn()) {
<button (click)="auth.logout()">Logout</button>
} @else {
<a routerLink="/login">Login</a>
}Authentication and Authorization
These two words sound similar but carry different meanings. Authentication answers the question "Who are you?" Authorization answers the question "What may you do?" A student and a teacher may both log in. Only the teacher may edit grades. Role checks in guards handle authorization on the screen, and the server must enforce the same rules.
Real-Life Example
An online school lets students log in to view marks. The student enters an email and password once. The server returns a token, and the app stores it in the service. Every request for marks carries that token, so the server knows which student asks. A teacher account receives a different token with extra permission, and the server uses it to allow grade changes.
Safety Reminders
- Always serve the login page over HTTPS.
- Never store passwords in the browser.
- Set short token lifetimes and refresh them when needed.
- Treat guards as a convenience, because the server decides who may read data.
Practice Exercise
Create a fake login that accepts one fixed email and password. Build the login page, the guard, and a dashboard route. Try to open the dashboard address without logging in and confirm that the app redirects you. Then log in and confirm that the dashboard opens.
Key Points
- A token acts as proof of login, like a concert wristband.
- The auth service logs in, stores the token, and reports the state.
- An interceptor adds the token, and a guard protects pages.
- The server must verify permission on every request.
