[英]How to get the token from firebase_auth
I'd like to get the auth token from firebase (email and password auth) to authenticate in my firebase cloud function. It seems like the functions getIdToken() and getToken() are both not working for firebase_auth package.我想从 firebase(电子邮件和密码身份验证)获取身份验证令牌以在我的 firebase 云 function 中进行身份验证。函数 getIdToken() 和 getToken() 似乎都不适用于 firebase_auth package。
is there an other function or is there even a better idea to make sure only authenticated users can trigger the cloud functions?还有其他 function 还是有更好的主意来确保只有经过身份验证的用户才能触发云功能?
var token = await FirebaseAuth.instance.currentUser.getIdToken();
var response = await httpClient.get(url,headers: {'Authorization':"Bearer $token"});
I agree with @Doug on this one - callable wraps this for you and will be easier -, but my use case required me to make HTTPS calls ( onRequest
in Functions).我同意@Doug 对此的看法 - callable 为您包装了它并且会更容易 - 但我的用例要求我进行 HTTPS 调用(函数中的
onRequest
)。 Also, I think you're just in the correct path - but you're possibly not checking it in your Cloud Functions.另外,我认为您只是在正确的路径上 - 但您可能没有在 Cloud Functions 中检查它。
In your app, you'll call:在您的应用程序中,您将调用:
_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);
});
}
In your function, you'll check for the token:在您的函数中,您将检查令牌:
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!" })
})
Keep in mind:记住:
If I'm not mistaken, those tokens are valid for 1 hour, if you are going to store them somewhere, just be aware of this.如果我没记错的话,这些令牌的有效期为 1 小时,如果您要将它们存储在某个地方,请注意这一点。 I've tested locally and i t takes around 200~500ms - every time - to get only the id token, which in most cases are not that big of overhead - but is significant.
我已经在本地进行了测试,每次都需要大约 200~500 毫秒才能获得 id 令牌,这在大多数情况下并不是那么大的开销 - 但很重要。
It's going to be easiest for you to use a callable function , since that lets you:使用可调用函数对您来说将是最简单的,因为它可以让您:
The flutter plugin is here .颤振插件在这里。
You should be able to do the equivalent work yourself, though, since callable functions are just a wrapper around normal HTTP connections.不过,您应该能够自己完成等效的工作,因为可调用函数只是普通 HTTP 连接的包装器。 It's possible for you to get the ID token of the logged in user.
您可以获取登录用户的 ID 令牌。
import 'package:firebase_messaging/firebase_messaging.dart';
.
.
.
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
@override
Future<void> initState() {
super.initState();
_firebaseMessaging.getToken().then((token) {
assert(token != null);
print("teken is: " + token);
});
}
Get your token from firebaseAuth and put in a string.从 firebaseAuth 获取您的令牌并放入一个字符串中。
Future<Details> getDetails() async {
String bearer = await FirebaseAuth.instance.currentUser!.getIdToken();
print("Bearer: " + bearer.toString());
String token = "Bearer ${bearer}";
var apiUrl = Uri.parse('Your url here');
final response = await http.get(apiUrl, headers: {
'Authorization' : '${token}'
});
final responseJson = jsonDecode(response.body);
return Details.fromJson(responseJson);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.