5

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.

1 Answer 1

4

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)

1
  • Is there a way to handle this for both proxied and non-proxied environments? I've looked at this question 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, 2021 at 11:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.