Reputation: 1
Issue with Setting Decrypted Token in Nest.JS Auth Guard
I am facing an issue in my Nest.JS application when handling HTTP-only tokens. I retrieve an encrypted token from the cookies, decrypt it, and then try to set it in the request header. However, instead of the decrypted token, the encrypted one gets set in the header.
// Check for the presence of the token
if (!encryptedToken) {
throw new ForbiddenException('Access denied. You need to be logged in.');
}
let decryptedToken: string;
try {
decryptedToken = this.decrypt(encryptedToken);
console.log("decryptedToken:", decryptedToken);
} catch (error) {
console.error("Decryption error:", error);
throw new ForbiddenException('Access denied. Invalid token.');
}
// Attempt to set decrypted token in Authorization header
request.headers['authorization'] = `Bearer ${decryptedToken}`;
// Call the parent canActivate method
const canActivate = await super.canActivate(context);
console.log("canActivate", canActivate);
// Check if canActivate returns an Observable
if (canActivate instanceof Observable) {
return canActivate.toPromise().then(result => result);
}
// Verify user role
const user = request.user;
if (user && user.role !== UserRole.KARJOO) {
throw new ForbiddenException('Access is only allowed for job seekers.');
}
return canActivate;
}
private decrypt(encryptedText: string): string {
const decipher = crypto.createDecipheriv(
'aes-256-cbc',
Buffer.from(process.env.AES_SECRET_KEY, 'hex'),
Buffer.from(process.env.AES_IV, 'hex')
);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
Upvotes: 0
Views: 40