![](/img/trans.png)
[英]How to trigger google cloud function with restricted Ip address?
[英]How to get client IP address in a Firebase cloud function?
When saving data to Firebase database with a Firebase cloud function, I'd like to also write the IP address where the request comes from.
但是, req.connection.remoteAddress
总是返回::ffff:0.0.0.0
。 有没有办法获取发出请求的客户端的实际 IP 地址?
编辑:这似乎已经过时了。 见另一个答案。
IP 地址似乎在req.headers["x-forwarded-for"]
可用。 不过,我没有在文档中找到这方面的官方信息。
另请注意,如果客户端本身发送例如X-Forwarded-For: 1.2.3.4
,则这些值将被连接:
"x-forwarded-for":"1.2.3.4, actual-client-ip-as-seen-by-google"
如果您正在寻找通过 firebase 托管的客户端 ip,您应该使用标头fastly-client-ip
将有真正的客户端 ip。
客户端 IP 在request.ip
。
示例:
export const pay = functions.https.onRequest((request, response) => {
console.log(`My IP is ${request.ip}`);
});
如果您正在云可调用函数中查找 ip 地址或标头,那么您可以在上下文对象中获取信息。
例如:
exports.testUser = async (data, context) => {
console.log('------------------------::context::------------------');
if(context.rawRequest && context.rawRequest.headers){
console.log(context.rawRequest.headers);
}
}
在标题中,您可以获得 ip : header { 'x-appengine-user-ip' : 'xxip' } 等。
这对我有用:
const express = require('express');
const logIP = async (req : any, res : any, next : any) => {
const clientIP = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.headers['fastly-client-ip'];
}
const logIPApp = express();
logIPApp.use(logIP);
exports.reportIP = functions.https.onRequest(logIPApp);
这就是使用 Firebase 云函数对我有用的方法:
const clientIP = req.headers['x-appengine-user-ip'] || req.header['x-forwarded-for']
请注意,这在本地不起作用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.