1

I want to build simple authentication using IP addresses, some IP address that I whitelisted can access the API. But I got a problem when I use request.ip it only output ::1 which is not a real IP address.

How to get the user IP Address in nestjs? Here are my code right now


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:

Turns out that ::1 are valid address for 'localhost' but when I deploy it on server and access the app from browser its log ::ffff:127.0.0.1 not my real IP.

mandaputtra
  • 588
  • 8
  • 20

1 Answers1

3

As I mentioned on Discord, you can use the header X-Forwarded-For as you're using nginx as a reverse proxy. The reason for getting ::1 is because that's the IP that the proxy is running on (i.e. localhost or 127.0.0.1)

Jay McDoniel
  • 18,659
  • 3
  • 29
  • 44
  • Is there a way to handle this for both proxied and non-proxied environments? I've looked at this [question](https://stackoverflow.com/questions/10849687/express-js-how-to-get-remote-client-address) but typescript complains about `string | string[]` when I try to remove the IPv6 mask (`::ffff:x.x.x.x`). Using a type guard was mentioned, but I'm sure there's an elegant, straightforward solution I'm missing – Kieran101 Feb 27 '21 at 11:00