From b4e3bf9f21aa9e3884c6c45960f8a5765bc91b4e Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Tue, 3 Nov 2026 17:03:07 +0600 Subject: [PATCH] TFA + JWT token manage in cookie --- CLAUDE.md | 14 +++++++++++--- HRM.UI/ClientApp/angular.json | 3 ++- HRM.UI/ClientApp/proxy.json | 8 ++++++++ .../src/app/_services/auth/auth.service.ts | 2 ++ HRM.UI/ClientApp/src/app/app.api.service.ts | 11 ++++++++++- HRM.UI/ClientApp/src/app/app.module.ts | 6 ++++++ HRM.UI/ClientApp/src/environments/environment.ts | 4 +++- HRM.UI/Controllers/Auth/AuthController.cs | 15 +++++++++++++++ HRM.UI/Controllers/Payroll/SalaryController.cs | 9 +++++++++ HRM.UI/Startup.cs | 12 ++++++++++++ 10 files changed, 78 insertions(+), 6 deletions(-) create mode 100644 HRM.UI/ClientApp/proxy.json diff --git a/CLAUDE.md b/CLAUDE.md index 5a88b94..601991f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -630,9 +630,17 @@ What the earlier 19 → 21 upgrade fixed in place, so don't undo it: `hrmopen-ai`, `calendar`, `survey`, …), each under `src/app//` with its own `.module.ts`. - `app.api.service.ts` (`ApiService`) is the single HTTP wrapper (`httpGet`, `httpPost`, `httpPostFile`, `httpDownloadFile`, …). The base URL comes from `environment.apiBaseUrl` - (`src/environments/environment.ts` → `https://localhost:44374/api`) in dev, and from the page's - `` + `api` in production. The auth token is a **static** `ApiService.AuthenticationToken` - sent as a Bearer header. + (`src/environments/environment.ts` → relative `/api`) in dev — `proxy.json` (the `serve` + `proxyConfig`) forwards it to `https://localhost:44374` — and from the page's `` + `api` + in production. +- **Auth is cookie-based (MFA work, ported from GP_Master).** `AuthController.CreateTokenNew` puts the + real JWT in the HttpOnly, `Secure`, `SameSite=Strict` `JWToken` cookie and returns only a + dummy-key copy, which the SPA keeps in `localStorage`/`ApiService.AuthenticationToken` for reading + claims and sends as the Bearer header. `Startup`'s `JwtBearerEvents.OnMessageReceived` lets the + cookie win over that header; `CredentialsInterceptor` (`app.api.service.ts`) adds + `withCredentials`; month-end (`SalaryController.GenerateTokenAfterMonthEnd`) re-sets the cookie; + `api/Authentication/logOut` deletes it. So the API must stay **same-origin** with the page: never + point the dev base URL back at an absolute `https://localhost:44374`, or every call after login is 401. - Shared code: `_guards/`, `_models//`, `_services//`, `picker/`/`_picker/`/ `dynamic-picker/`, `custom-components/`, `form-builder/`, `helper/`, `SharedIconModule/`. - The UI kit is **Kendo UI Angular** (`@progress/kendo-angular-*`, licensed) plus chart.js, sweetalert2, the two diff --git a/HRM.UI/ClientApp/angular.json b/HRM.UI/ClientApp/angular.json index 97c8ec7..3cfdb44 100644 --- a/HRM.UI/ClientApp/angular.json +++ b/HRM.UI/ClientApp/angular.json @@ -91,7 +91,8 @@ "serve": { "builder": "@angular/build:dev-server", "options": { - "buildTarget": "babylon:build" + "buildTarget": "babylon:build", + "proxyConfig": "proxy.json" }, "configurations": { "production": { diff --git a/HRM.UI/ClientApp/proxy.json b/HRM.UI/ClientApp/proxy.json new file mode 100644 index 0000000..0c14b85 --- /dev/null +++ b/HRM.UI/ClientApp/proxy.json @@ -0,0 +1,8 @@ +{ + "/api": { + "target": "https://localhost:44374", + "secure": false, + "changeOrigin": true, + "logLevel": "debug" + } +} diff --git a/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts b/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts index 19ad453..52f2c6c 100644 --- a/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts @@ -121,6 +121,8 @@ export class AuthService { sessionStorage.removeItem('employeeCommonData'); this.logoutSource.next(); this.router.navigate(['/login']); + // Clear the HttpOnly JWToken cookie on the server; logout must never fail because of it. + this.apiService.httpPost('/Authentication/logOut', {}).subscribe({ error: () => {} }); } SaveUser(oUser: User): any { return this.apiService.httpPost('/Authentication/SaveUser', oUser); diff --git a/HRM.UI/ClientApp/src/app/app.api.service.ts b/HRM.UI/ClientApp/src/app/app.api.service.ts index 5bf29d8..02513a2 100644 --- a/HRM.UI/ClientApp/src/app/app.api.service.ts +++ b/HRM.UI/ClientApp/src/app/app.api.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { Observable, Subject, throwError } from 'rxjs'; -import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; +import { HttpClient, HttpHeaders, HttpErrorResponse, HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { catchError, retry } from 'rxjs/operators'; import { DatePipe } from '@angular/common'; import { GlobalfunctionExtension } from './_models/globalFunctions'; @@ -285,3 +285,12 @@ export class PubSubService { @Injectable() export class BaseHrefService { } + +// Sends cookies with every request (including AuthService's direct HttpClient calls), so the +// HttpOnly "JWToken" cookie set at login is stored and sent back to the API. +@Injectable() +export class CredentialsInterceptor implements HttpInterceptor { + intercept(req: HttpRequest, next: HttpHandler): Observable> { + return next.handle(req.clone({ withCredentials: true })); + } +} diff --git a/HRM.UI/ClientApp/src/app/app.module.ts b/HRM.UI/ClientApp/src/app/app.module.ts index 55f0df4..9c87826 100644 --- a/HRM.UI/ClientApp/src/app/app.module.ts +++ b/HRM.UI/ClientApp/src/app/app.module.ts @@ -71,6 +71,7 @@ import {NgxExtendedPdfViewerModule} from 'ngx-extended-pdf-viewer'; import {ProgressBarModule} from '@progress/kendo-angular-progressbar'; import {MsalGuard, MsalInterceptor, MsalModule, MsalRedirectComponent, MsalService} from '@azure/msal-angular'; import {InteractionType, PublicClientApplication} from '@azure/msal-browser'; +import { CredentialsInterceptor } from './app.api.service'; import { BackgroundCanvasModule } from './BackgroundCanvas/BackgroundCanvas.module'; import { VersionCheckService } from './version-check.service'; import { EssModule } from './ess/ess.module'; @@ -206,6 +207,11 @@ import { EmpCommonInformationModule } from './ess/emp-common-information/EmpComm useClass: MsalInterceptor, multi: true }, + { + provide: HTTP_INTERCEPTORS, + useClass: CredentialsInterceptor, + multi: true + }, MsalService, MenuService, NotificationTriggerService, BreadcrumbService, diff --git a/HRM.UI/ClientApp/src/environments/environment.ts b/HRM.UI/ClientApp/src/environments/environment.ts index 8684cb5..48b9ddc 100644 --- a/HRM.UI/ClientApp/src/environments/environment.ts +++ b/HRM.UI/ClientApp/src/environments/environment.ts @@ -6,7 +6,9 @@ export const environment = { production: false, // Used by ApiService only in dev mode (ng serve). In production the API // base URL is derived from in index.html instead. - apiBaseUrl: 'https://localhost:44374/api' + // Relative on purpose: on ng serve, proxy.json forwards /api to https://localhost:44374, so the + // API is same-origin and the HttpOnly SameSite=Strict "JWToken" auth cookie is stored and sent. + apiBaseUrl: '/api' }; /* diff --git a/HRM.UI/Controllers/Auth/AuthController.cs b/HRM.UI/Controllers/Auth/AuthController.cs index 3249940..a5b75af 100644 --- a/HRM.UI/Controllers/Auth/AuthController.cs +++ b/HRM.UI/Controllers/Auth/AuthController.cs @@ -701,6 +701,21 @@ namespace HRM.UI.Controllers return Ok(new { userToken }); } + // Clears the HttpOnly "JWToken" cookie the API authenticates from (see Startup), so the + // session really ends on logout. Anonymous so an invalid/expired cookie can still be removed. + [HttpPost("logOut")] + [AllowAnonymous] + public IActionResult logOut() + { + Response.Cookies.Delete("JWToken", new CookieOptions + { + HttpOnly = true, + Secure = true, + SameSite = SameSiteMode.Strict + }); + return Ok(); + } + [HttpPost("resend-otp")] [EnableRateLimiting("ResendOtpPolicy")] [AllowAnonymous] diff --git a/HRM.UI/Controllers/Payroll/SalaryController.cs b/HRM.UI/Controllers/Payroll/SalaryController.cs index bf1393a..ecd9cb6 100644 --- a/HRM.UI/Controllers/Payroll/SalaryController.cs +++ b/HRM.UI/Controllers/Payroll/SalaryController.cs @@ -1408,6 +1408,15 @@ namespace HRM.UI.Controllers.Payroll var token = tokenHandler.CreateToken(tokenDescriptor); string tokenString = tokenHandler.WriteToken(token); HttpContext.Session.SetString("JWToken", tokenString); + // The API authenticates from the "JWToken" cookie first (Startup), so the new + // process date only takes effect once the cookie carries the new token too. + Response.Cookies.Append("JWToken", tokenString, new CookieOptions + { + HttpOnly = true, + Secure = true, + SameSite = SameSiteMode.Strict, + Expires = DateTimeOffset.Now.AddDays(1) + }); return tokenString; } diff --git a/HRM.UI/Startup.cs b/HRM.UI/Startup.cs index 7714edf..6faad6a 100644 --- a/HRM.UI/Startup.cs +++ b/HRM.UI/Startup.cs @@ -242,6 +242,18 @@ namespace HRM.UI.Api ValidateIssuer = false, ValidateAudience = false }; + options.Events = new JwtBearerEvents + { + OnMessageReceived = context => + { + var cookieToken = context.Request.Cookies["JWToken"]; + if (!string.IsNullOrEmpty(cookieToken)) + { + context.Token = cookieToken; + } + return System.Threading.Tasks.Task.CompletedTask; + } + }; }); #endregion