简体   繁体   中英

Get user's IP address from firebase auth trigger?

How can we get the user's IP address when using functions.auth.user().onCreate(...) ? Basically, I want to track the IP address from when a user visits our website and the IP address from when they sign up on the app for analytics purposes, unless someone knows a better way. Thanks.

This is not possible in any Cloud Functions background trigger. If you want to attempt to record an IP address (which may not be very accurate or helpful, given that network traffic can go through proxies and VPNs), you will have to use an HTTP type trigger that was invoked from your app or web site running on the the user's computer or device. The request might include a header called x-forwarded-for or fastly-client-ip that contains an IP address. But this isn't documented, so there is no guarantee this will exist.

See also: How to get client IP address in a Firebase cloud function?

The IP information is available from Firebase auth using the EventContext object from auth.user().beforeSignIn() as well as auth.user().beforeCreate()

To use it, you'll first need to upgrade to Firebase Authentication with Identity Platform . It's available in both Spark & Blaze plans and can be enabled by going to 'Firebase Authentication -> Settings' in your project.

The docs give the following use-case for getting, checking, and blocking based on IP from auth.user().beforeSignIn() for example:

exports.beforeSignIn = functions.auth.user().beforeSignIn((user, 
context) => {
  if (isSuspiciousIpAddress(context.ipAddress)) {
    throw new functions.auth.HttpsError(
      'permission-denied', 'Unauthorized access!');
  }
});

For more details and examples of what else is available in the EventContext, see Getting user and context information .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM