fix: Include configured API host in allowed hosts for auth interceptor

Token was not being attached to requests on VM deployments because
the IP address wasn't in the hardcoded allowedHosts list.

Now dynamically adds the host from RuntimeConfigService.apiBaseUrl
to the allowed list, fixing 401 errors on remote deployments.
This commit is contained in:
Mahi
2026-02-09 14:49:48 -04:00
parent 31419f49b1
commit 24d5625d17

View File

@@ -3,6 +3,7 @@ import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { StorageService } from '../services/storage.service';
import { TokenValidator } from '../utils/token-validator';
import { RuntimeConfigService } from '../services/runtime-config.service';
/**
* Auth Interceptor with Security Enhancements
@@ -16,14 +17,15 @@ import { TokenValidator } from '../utils/token-validator';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const storage = inject(StorageService);
const router = inject(Router);
const runtimeConfig = inject(RuntimeConfigService);
// Skip token attachment for auth endpoints (login/register)
if (isAuthEndpoint(req.url)) {
return next(req);
}
// Only attach tokens to our API
if (!isInternalApiRequest(req)) {
// Only attach tokens to our API (includes configured runtime API URL)
if (!isInternalApiRequest(req, runtimeConfig.apiBaseUrl)) {
return next(req);
}
@@ -87,7 +89,7 @@ function isAuthEndpoint(url: string): boolean {
* Check if request is to our internal API
* Prevents token leakage to external services
*/
function isInternalApiRequest(req: HttpRequest<unknown>): boolean {
function isInternalApiRequest(req: HttpRequest<unknown>, configuredApiUrl: string): boolean {
const url = req.url.toLowerCase();
// List of allowed API hosts
@@ -98,6 +100,16 @@ function isInternalApiRequest(req: HttpRequest<unknown>): boolean {
'staging-api.goagel.gov.in', // Staging API
];
// Add configured API host dynamically (for VM/remote deployments)
try {
const configuredUrl = new URL(configuredApiUrl);
if (configuredUrl.hostname && !allowedHosts.includes(configuredUrl.hostname)) {
allowedHosts.push(configuredUrl.hostname);
}
} catch {
// Invalid configured URL - ignore
}
try {
const requestUrl = new URL(url, window.location.origin);
return allowedHosts.some(