Skip to content

Latest commit

 

History

History
156 lines (114 loc) · 4.45 KB

jwt.md

File metadata and controls

156 lines (114 loc) · 4.45 KB

JWT Authentication

Auth API: authentication.API -- ASP.NET Core 8, port 7251 Frontend: foodloop-ui/src/app/auth/


Overview

FoodLoopSuite uses JSON Web Tokens (JWT) for stateless authentication. The Angular SPA authenticates against a dedicated authentication.API microservice, stores the token in localStorage, and attaches it to every subsequent request via an HTTP interceptor.

Browser --POST /login--> authentication.API --> returns { token }
           store in localStorage
Browser --GET /api/...--> coreAPI
           Authorization: Bearer <token>  (injected by authInterceptor)

Flow

1. Login / Register

Endpoint Method Body
/api/auth/login POST { email, password }
/api/auth/register POST { email, password, name }

Both return { token: string } on success. AuthService stores the token and sets the isLoggedIn signal to true.

// auth.service.ts
login(request: LoginRequest) {
  return this.http.post<AuthResponse>(${this.apiUrl}/login, request).pipe(
    tap(response => this.storeToken(response.token))
  );
}

2. Token storage

private readonly tokenKey = 'auth_token';

// stored in:
localStorage.setItem('auth_token', token);

// retrieved by interceptor on every request:
localStorage.getItem('auth_token');

Security note: localStorage is accessible to any JavaScript running on the page. For higher-security deployments consider httpOnly cookies instead.

3. HTTP Interceptor

Every outgoing HTTP request automatically receives an Authorization header:

// auth.interceptor.ts
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = auth.getToken();

  const authedReq = token
    ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
    : req;

  return next(authedReq).pipe(
    catchError(err => {
      if (err.status === 401) auth.logout();   // auto-logout on 401
      return throwError(() => err);
    })
  );
};

A 401 response from the API automatically calls auth.logout() --- clears the token and redirects to /login.

4. Route Guard

Protected routes (/pos, /master) are gated by authGuard:

// auth.guard.ts
export const authGuard: CanActivateFn = () => {
  if (auth.hasValidToken()) return true;
  return router.createUrlTree(['/login']);   // redirect if no valid token
};

hasValidToken() checks both that a token exists and that it is not expired by reading the exp claim from the JWT payload.

5. Idle timeout

AuthService implements a 30-minute inactivity timeout:

Config constant Value Description
IDLE_TIMEOUT_MS 30 min Time of inactivity before auto-logout
WARN_BEFORE_MS 60 s Show countdown warning this long before logout
RESET_THROTTLE_MS 10 s Minimum interval between activity resets (throttle)
  • User activity (mouse move, keydown, click) resets the idle timer.
  • The idleWarning signal becomes true when 60 s remain --- the UI renders a countdown banner.
  • The idleCountdown signal counts down the remaining seconds for the banner to display.
  • At expiry, logout() is called automatically.

Key files

File Role
auth/auth.service.ts Login, register, logout, token storage, idle timer
auth/auth.interceptor.ts Attaches Bearer token, handles 401 auto-logout
auth/auth.guard.ts CanActivateFn --- blocks unauthenticated access to /pos + /master
auth/login/login.component.ts Login form UI
auth/register/register.component.ts Register form UI
models/auth.models.ts LoginRequest, RegisterRequest, AuthResponse interfaces

Token expiry check

The token expiry is decoded client-side from the JWT payload:

isTokenExpired(): boolean {
  const token = this.getToken();
  if (!token) return true;
  const payload = JSON.parse(atob(token.split('.')[1]));
  return payload.exp * 1000 < Date.now();
}

The exp claim is a Unix timestamp (seconds). Multiplying by 1000 converts to milliseconds for Date.now() comparison.


Registering the interceptor

The interceptor is registered in app.config.ts using the functional interceptor API (Angular 15+):

// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([authInterceptor])),
    provideRouter(routes),
    ...
  ]
};