【发布时间】:2022-01-07 12:38:02
【问题描述】:
我正在尝试调用托管后端的 Firebase 函数的 api 端点,但我遇到了困难。
这是我的端点的代码:
app.post("/hello", (req,res) => {
console.log(req.headers);
res.status(200).json({
message: "Hello"
})
})
我还使用这样的中间件设置了对身份验证令牌的检查:
app.use(validateFirebaseIdToken);
const validateFirebaseIdToken = async (req,res,next) => {
console.log(req);
functions.logger.log('Check if request is authorized with Firebase ID token');
if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
!(req.cookies && req.cookies.__session)) {
functions.logger.error(
'No Firebase ID token was passed as a Bearer token in the Authorization header.',
'Make sure you authorize your request by providing the following HTTP header:',
'Authorization: Bearer <Firebase ID Token>',
'or by passing a "__session" cookie.'
);
res.status(403).send('Unauthorized');
return;
}
let idToken;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
functions.logger.log('Found "Authorization" header');
// Read the ID Token from the Authorization header.
idToken = req.headers.authorization.split('Bearer ')[1];
} else if(req.cookies) {
functions.logger.log('Found "__session" cookie');
// Read the ID Token from cookie.
idToken = req.cookies.__session;
} else {
// No cookie
res.status(403).send('Unauthorized');
return;
}
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken);
functions.logger.log('ID Token correctly decoded', decodedIdToken);
req.user = decodedIdToken;
next();
return;
} catch (error) {
functions.logger.error('Error while verifying Firebase ID token:', error);
res.status(403).send('Unauthorized');
return;
}
}
在我的 axios 请求中,我正在这样做:
const headerAPI = {
withCredentials: true,
Authorization: `Bearer ${myToken}`
}
allInfo = await axios.post('http://localhost:5001/stormtestfordota/europe-west1/api/hello', headerAPI);
但即使我输入了正确的身份验证令牌,我也会在控制台中收到此令牌
{"severity":"INFO","message":"检查请求是否使用 Firebase ID 令牌授权"} {"severity":"ERROR","message":"在 Authorization 标头中没有 Firebase ID 令牌作为 Bearer 令牌传递。确保通过提供以下 HTTP 标头来授权您的请求:授权:Bearer 或通过传递“ __session" cookie。"}
在我的浏览器中我得到了这个错误:
CORS 策略阻止了从源“http://localhost:3000”访问“http://localhost:5001/stormtestfordota/europe-west1/api/hello”处的 XMLHttpRequest:对预检请求的响应没有“ t 通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
即使我为 localhost:3000 启用了 CORS 策略。
你知道为什么会这样吗?
【问题讨论】:
-
标题应该嵌套在“标题”属性下。另外,您的帖子有效负载在哪里?
标签: node.js axios firebase-authentication google-cloud-functions