I'm looking to implement a basic authentication system using IP addresses, where only whitelisted IPs can access the API. However, I've encountered an issue with obtaining the user's actual IP address when using request.ip
, as it only returns ::1
which is not a valid IP.
How can I retrieve the user's IP Address in nestjs? Below is my current code:
import {
Injectable,
CanActivate,
ExecutionContext,
Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
const allowedIp: Array<string> = ['129.2.2.2', '129.2.2.2'];
if (process.env.ENV === 'production') {
const ip = request.connection.remoteAddress;
Logger.log(ip, 'ACCESSED IP ADDRESS');
if (allowedIp.includes(ip)) {
return true;
} else {
return false;
}
} else {
return true;
}
}
}
Edit:
It appears that ::1
is a valid address for 'localhost'. However, when deployed on a server and accessed from a browser, it logs ::ffff:127.0.0.1
instead of the real IP address.