Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 74 ยท Projects

Project: Admin Dashboard with Auth

Build an Angular admin dashboard with a login flow, an auth interceptor, role-based route guards and a sortable, filterable users table driven by signals. Runnable stand-ins included.

Admin dashboards are where several Angular features meet: a login flow, requests that must carry a credential, pages that only some roles may open, and big data tables that users sort and filter. They are also where mistakes are expensive, so this project spends as much time on what the client can not guarantee as on what it can.

We build four pieces: an auth service that keeps the session in a signal, an HTTP interceptor that attaches the token and reacts to 401 answers, route guards for login and roles, and a users table with sort and filter signals. The foundations are in HTTP Interceptors, Guards, Resolvers and Router Events and Signals in Components.

The client is not a security boundary. Everything that runs in a browser can be inspected and changed by the user. Guards and hidden buttons make the interface sensible; the server must check authentication and permissions on every request. Never rely on a client-side role check to protect data.

Real versus stand-in. The typescript and html blocks are real Angular code and read-only, because this site cannot run the Angular compiler or a login server. The runnable examples are stand-ins: a fake backend, a small interceptor chain, guard functions and a tiny signal implementation, all as plain TypeScript with deterministic output.

The plan

sequenceDiagram
  participant U as User
  participant G as Guards
  participant A as AuthService
  participant I as Interceptor
  participant S as Server
  U->>G: open /admin/users
  G->>A: logged in?
  A-->>G: no
  G-->>U: redirect to /login?returnUrl=/admin/users
  U->>A: login(email, password)
  A->>I: POST /api/login
  I->>S: request (no token)
  S-->>A: token + user
  U->>G: open /admin/users again
  G->>A: logged in and role allowed?
  A-->>G: yes
  U->>I: GET /api/users
  I->>S: request + Authorization header
  S-->>U: users

The guard decides whether a page may open; the interceptor decides what each request carries; the server decides whether to answer.

Step 1: the auth service

The session (token plus user) is one signal. Whether someone is logged in, who they are and which role they have are all derived with computed(), so they can never disagree with each other.

TypeScript
// auth.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable, computed, inject, signal } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, map, tap } from 'rxjs';

export type Role = 'admin' | 'editor' | 'viewer';

export interface User {
  id: number;
  name: string;
  role: Role;
}

interface LoginResponse {
  token: string;
  user: User;
}

@Injectable({ providedIn: 'root' })
export class AuthService {
  private readonly http = inject(HttpClient);
  private readonly router = inject(Router);

  private readonly session = signal<LoginResponse | null>(null);

  readonly user = computed(() => this.session()?.user ?? null);
  readonly token = computed(() => this.session()?.token ?? null);
  readonly isLoggedIn = computed(() => this.session() !== null);

  login(email: string, password: string): Observable<User> {
    return this.http.post<LoginResponse>('/api/login', { email, password }).pipe(
      tap(response => this.session.set(response)),
      map(response => response.user),
    );
  }

  logout(): void {
    this.session.set(null);
    this.router.navigateByUrl('/login');
  }

  hasRole(...roles: Role[]): boolean {
    const user = this.user();
    return user !== null && roles.includes(user.role);
  }
}

Where does the token live? Here it is kept in memory only. That is the safest place against script injection (a stolen localStorage token works from anywhere), but it is lost on reload, so the user logs in again. Production apps usually go further: the server sets the session in an HttpOnly, Secure, SameSite cookie that scripts cannot read, the app calls the API with withCredentials, and Angular's XSRF support handles the matching header. Storage choices are covered in Security and Accessibility; the structure of this project works with either approach.

Step 2: the login form and the return URL

A reactive form collects the credentials. After a successful login the user goes back to the page they originally wanted, which the guard stored as a returnUrl query parameter.

TypeScript
// login.ts
import { Component, inject, input, signal } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-login',
  imports: [ReactiveFormsModule],
  templateUrl: './login.html',
})
export class Login {
  private readonly auth = inject(AuthService);
  private readonly router = inject(Router);
  private readonly fb = inject(NonNullableFormBuilder);

  readonly returnUrl = input<string>();   // bound from ?returnUrl=... (withComponentInputBinding)
  protected readonly failed = signal(false);

  protected readonly form = this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    password: ['', Validators.required],
  });

  protected submit(): void {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    const { email, password } = this.form.getRawValue();
    this.auth.login(email, password).subscribe({
      next: () => this.router.navigateByUrl(this.safeTarget()),
      error: () => this.failed.set(true),
    });
  }

  private safeTarget(): string {
    const target = this.returnUrl() ?? '';
    return target.startsWith('/') && !target.startsWith('//') ? target : '/admin';
  }
}

safeTarget() matters: a link such as /login?returnUrl=https://evil.example must not send the user off-site after login. Accepting only local paths (starting with one slash) prevents that open redirect. The error message should be vague ("Email or password is wrong") and identical for unknown users and wrong passwords, so the form does not reveal which emails exist.

Step 3: an interceptor for the token and for 401

Adding Authorization by hand to every call would be forgotten sooner or later. One functional interceptor does it for all of them, and it also handles the case where the server says the session is no longer valid.

TypeScript
// auth.interceptor.ts
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { catchError, throwError } from 'rxjs';
import { AuthService } from './auth.service';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(AuthService);
  const token = auth.token();

  const isOurApi = req.url.startsWith('/api/');
  const isLogin = req.url === '/api/login';

  const outgoing =
    token && isOurApi && !isLogin
      ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
      : req;

  return next(outgoing).pipe(
    catchError((error: unknown) => {
      if (error instanceof HttpErrorResponse && error.status === 401 && token) {
        auth.logout();
      }
      return throwError(() => error);
    }),
  );
};
TypeScript
// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes, withComponentInputBinding()),
    provideHttpClient(withInterceptors([authInterceptor])),
  ],
};

Two details prevent real bugs. The interceptor only adds the token to your own API (/api/): sending the token to a third-party URL would leak it. And it never adds it to the login request. Requests are immutable, which is why req.clone() is needed. Interceptors run in the order of the array, so one registered before another sees the request first and the response last.

The first runnable example is a stand-in for the whole flow: a fake backend, an auth state, an interceptor chain, guards, and a user who logs in, is refused, and finally has the session revoked.

TypeScript Login, interceptor and role guards against a fake server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read it step by step. Without a session the guard redirects to the login page and remembers where you wanted to go. The failed login returns a 401 while there is no token, so the interceptor does not log anyone out; with a token, a 401 means the session is dead and logout() runs. The viewer can see no admin pages, even though the dashboard code is the same. The logging interceptor sits after the auth interceptor in the chain, so it sees the header that was added.

Step 4: role guards in the route table

The guards from the stand-in are small functions. In Angular, a guard factory returns a CanActivateFn, so the allowed roles are written right where the route is declared:

TypeScript
// guards.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService, Role } from './auth.service';

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthService);
  const router = inject(Router);
  return auth.isLoggedIn()
    ? true
    : router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};

export const roleGuard = (...roles: Role[]): CanActivateFn => () => {
  const auth = inject(AuthService);
  const router = inject(Router);
  return auth.hasRole(...roles) ? true : router.createUrlTree(['/forbidden']);
};
TypeScript
// app.routes.ts
export const routes: Routes = [
  { path: 'login', loadComponent: () => import('./login').then(m => m.Login) },
  { path: 'forbidden', loadComponent: () => import('./forbidden').then(m => m.Forbidden) },
  {
    path: 'admin',
    canActivate: [authGuard],
    children: [
      { path: '', pathMatch: 'full', redirectTo: 'users' },
      {
        path: 'users',
        canActivate: [roleGuard('admin', 'editor')],
        loadComponent: () => import('./users').then(m => m.Users),
      },
      {
        path: 'settings',
        canActivate: [roleGuard('admin')],
        loadComponent: () => import('./settings').then(m => m.Settings),
      },
    ],
  },
  { path: '**', redirectTo: 'login' },
];

The shell template can hide links the user may not open, with @if (auth.hasRole('admin')) { <a routerLink="/admin/settings">Settings</a> }. That is only polish: a hidden link does not protect the page, and the guard does not protect the data. The API behind /api/users has to enforce the same roles.

Step 5: a data table with sort and filter signals

The table needs three inputs: the filter text, the sort column and the direction. They are signals; the visible rows are one computed() over them. Nothing is stored twice and there is no "apply" step.

TypeScript
// users.ts
import { Component, computed, inject, signal } from '@angular/core';
import { UserService, UserRow } from './user.service';

type SortKey = 'name' | 'role' | 'lastLogin';

@Component({
  selector: 'app-users',
  templateUrl: './users.html',
})
export class Users {
  private readonly users = inject(UserService).users;   // a signal of UserRow[]

  protected readonly filter = signal('');
  protected readonly sortKey = signal<SortKey>('name');
  protected readonly sortDir = signal<'asc' | 'desc'>('asc');

  protected readonly rows = computed(() => {
    const query = this.filter().trim().toLowerCase();
    const key = this.sortKey();
    const direction = this.sortDir() === 'asc' ? 1 : -1;

    return this.users()
      .filter(u => !query || u.name.toLowerCase().includes(query) || u.role.includes(query))
      .sort((a, b) => {
        const byKey = a[key].localeCompare(b[key]);
        return byKey !== 0 ? byKey * direction : a.name.localeCompare(b.name);
      });
  });

  protected sortBy(key: SortKey): void {
    if (this.sortKey() === key) {
      this.sortDir.update(d => (d === 'asc' ? 'desc' : 'asc'));
    } else {
      this.sortKey.set(key);
      this.sortDir.set('asc');
    }
  }
}

Note that .filter() creates a new array, so the following .sort() does not reorder the original data held by the service. Calling .sort() directly on a signal's array would mutate shared state, a classic bug. The tiebreaker (sort by name when the keys are equal) keeps the order stable and predictable.

HTML
<!-- users.html -->
<label for="q">Filter</label>
<input id="q" type="search" [value]="filter()" (input)="filter.set($any($event.target).value)" />

<table>
  <thead>
    <tr>
      <th scope="col" [attr.aria-sort]="sortKey() === 'name' ? (sortDir() === 'asc' ? 'ascending' : 'descending') : 'none'">
        <button type="button" (click)="sortBy('name')">Name</button>
      </th>
      <th scope="col" [attr.aria-sort]="sortKey() === 'role' ? (sortDir() === 'asc' ? 'ascending' : 'descending') : 'none'">
        <button type="button" (click)="sortBy('role')">Role</button>
      </th>
      <th scope="col">Last login</th>
    </tr>
  </thead>
  <tbody>
    @for (u of rows(); track u.id) {
      <tr><td>{{ u.name }}</td><td>{{ u.role }}</td><td>{{ u.lastLogin }}</td></tr>
    } @empty {
      <tr><td colspan="3">No users match your filter.</td></tr>
    }
  </tbody>
</table>

The header text is a real <button>, so the sort works with the keyboard, and aria-sort tells screen readers which column is sorted and how. Tracking by u.id lets Angular move rows around instead of rebuilding them when the order changes. For tens of thousands of rows you would paginate on the server or use virtual scrolling, see Performance Tuning.

The second runnable example is the table logic with a tiny signal and computed, plus a counter showing how many times the rows were actually recalculated.

TypeScript A sortable, filterable table driven by signals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at the order after each click: clicking Name a second time reverses the order, clicking Role sorts by role and breaks ties by name, and Last login sorts dates as text, which works because the format is YYYY-MM-DD. The filter ignores case and surrounding spaces. Reading the rows repeatedly recalculates nothing, because the computed is cached until a signal it reads changes.

Ideas to extend it

  • Add server-side sorting and paging: the signals become the parameters of a resource() (linkedSignal, resource and httpResource).
  • Refresh tokens: on a 401 the interceptor could call a refresh endpoint once and retry, instead of logging out immediately. Guard against several requests refreshing at the same time.
  • Audit what each role may do with a table in your docs, and test it against the server, not only the guards.
  • Write tests for the guards and the interceptor, see Testing Components and Services.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the client-side role guard not enough to protect admin data?

    Guards and hidden links improve the experience. Authorization must be enforced by the server, because anyone can call the API without your UI.
  2. 2. Why does the auth interceptor only add the token to URLs that start with /api/?

    Attaching credentials to every request would send them to any host the app calls. Limit them to your own API.
  3. 3. What does the interceptor do when a request with a token comes back as 401?

    A 401 on an authenticated request means the server no longer accepts the token. Clearing the session and redirecting to login is the usual reaction.
  4. 4. Why does the login component only accept return URLs that start with one slash?

    A crafted link could carry a returnUrl to a malicious site. Accepting only local paths keeps the user inside your app.
  5. 5. Why does the table computed call filter() before sort()?

    Array.sort changes the array it is called on. Sorting the result of filter() works on a fresh copy; sorting the signal's own array would mutate shared state.

Summary

  • Keep the session in one signal and derive isLoggedIn, user and role checks with computed().
  • A functional interceptor adds the token to your own API only (never the login call or third-party hosts) and turns a 401 into a logout.
  • Guard factories such as roleGuard('admin') keep permissions next to the routes; returning a UrlTree redirects cleanly, and a returnUrl must be validated to avoid open redirects.
  • The client only improves the interface: authentication and authorization must be enforced by the server.
  • Sort, direction and filter are signals; the visible rows are one computed() that sorts a copy, with a tiebreaker for stable order and accessible headers (button plus aria-sort).

Next: Practice Exercises with Solutions.