Hell everyone,
since we don't have login feature for application we don't have user authentication and API are anonymous acces.
to handle this scenario we are passing static token in header and validating in server side but still it is not sufficient beacuse token is static
I need some help in creating dynamic secrets in angular and that shoul be validated in server side.
Let me know if any idea's on this.


Naimish MakwanaRank #324 · 7.7K reputationPosted Sep 16, 2024, 1:00 AM EDT
To enhance security in your application, you can implement dynamic secrets in Angular and validate them on the server side. Here are some steps and ideas to help you achieve this:
1. Generate Dynamic Secrets in Angular
You can use a combination of environment variables and a service to generate dynamic secrets.
Environment Variables
Store sensitive information in environment variables to avoid hardcoding them in your source code.
// environment.ts export const environment = { production: false, secretKey: 'your-secret-key' };Secret Generation Service
Create a service to generate dynamic secrets.
// secret.service.ts import { Injectable } from '@angular/core'; import { environment } from '../environments/environment'; import * as crypto from 'crypto-js'; @Injectable({ providedIn: 'root' }) export class SecretService { generateSecret(): string { const timestamp = new Date().getTime().toString(); return crypto.HmacSHA256(timestamp, environment.secretKey).toString(); } }2. Attach Secret to API Requests
Use an HTTP interceptor to attach the generated secret to your API requests.
// auth.interceptor.ts import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http'; import { SecretService } from './secret.service'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private secretService: SecretService) {} intercept(req: HttpRequest, next: HttpHandler) { const secret = this.secretService.generateSecret(); const clonedRequest = req.clone({ headers: req.headers.set('Authorization', `Bearer ${secret}`) }); return next.handle(clonedRequest); } }3. Validate Secret on Server Side
On the server side, validate the secret by comparing it with the expected value.
Example in Node.js
const crypto = require('crypto-js'); function validateSecret(req, res, next) { const secret = req.headers['authorization'].split(' ')[1]; const timestamp = new Date().getTime().toString(); const expectedSecret = crypto.HmacSHA256(timestamp, process.env.SECRET_KEY).toString(); if (secret === expectedSecret) { next(); } else { res.status(401).send('Unauthorized'); } }Thanks