Nel*_*eli 7 firebase-authentication flutter google-cloud-functions
我想从 firebase(电子邮件和密码身份验证)获取身份验证令牌以在我的 firebase 云功能中进行身份验证。似乎函数 getIdToken() 和 getToken() 都不适用于 firebase_auth 包。
是否有其他功能,或者是否有更好的主意来确保只有经过身份验证的用户才能触发云功能?
var token = await FirebaseAuth.instance.currentUser.getIdToken();
var response = await httpClient.get(url,headers: {'Authorization':"Bearer $token"});
Run Code Online (Sandbox Code Playgroud)
我同意@Doug 对此的看法 - callable 为您包装了它并且会更容易 - 但我的用例要求我进行 HTTPS 调用(onRequest在函数中)。另外,我认为您只是在正确的路径上 - 但您可能没有在 Cloud Functions 中检查它。
在您的应用程序中,您将调用:
_httpsCall() async {
// Fetch the currentUser, and then get its id token
final user = await FirebaseAuth.instance.currentUser();
final idToken = await user.getIdToken();
final token = idToken.token;
// Create authorization header
final header = { "authorization": 'Bearer $token' };
get("http://YOUR_PROJECT_BASE_URL/httpsFunction", headers: header)
.then((response) {
final status = response.statusCode;
print('STATUS CODE: $status');
})
.catchError((e) {
print(e);
});
}
Run Code Online (Sandbox Code Playgroud)
在您的函数中,您将检查令牌:
export const httpsFunction = functions.https.onRequest((request, response) => {
const authorization = request.header("authorization")
if (authorization) {
const idToken = authorization.split('Bearer ')[1]
if (!idToken) {
response.status(400).send({ response: "Unauthenticated request!" })
return
}
return admin.auth().verifyIdToken(idToken)
.then(decodedToken => {
// You can check for your custom claims here as well
response.status(200).send({ response: "Authenticated request!" })
})
.catch(err => {
response.status(400).send({ response: "Unauthenticated request!" })
})
}
response.status(400).send({ response: "Unauthenticated request!" })
})
Run Code Online (Sandbox Code Playgroud)
记住:
如果我没记错的话,这些令牌的有效期为 1 小时,如果您要将它们存储在某个地方,请注意这一点。我已经在本地进行了测试,每次都需要大约 200~500 毫秒才能仅获取 id 令牌,这在大多数情况下并不是那么大的开销 - 但很重要。
| 归档时间: |
|
| 查看次数: |
6617 次 |
| 最近记录: |