如何在Firebase中为社交登录创建包装REST API?
问题描述:
我正在尝试使用云功能为Firebase身份验证创建包装REST API。如何在Firebase中为社交登录创建包装REST API?
我怎么能创建用户或认证用户上火力地堡一旦我有(使用Facebook的SDK)在客户端Facebook的访问令牌?
答
如果您将Firebase函数与HTTP触发器一起使用,则可以使用firebase.js客户端node.js库对REST API中的用户进行身份验证并返回Firbease令牌。您可以将Facebook Access令牌发送到该HTTP端点,使用node.js客户端库以signInWithCredential
登录该用户,并返回ID令牌和刷新令牌。
如果你想使用REST API:
curl 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyAssertion?key=[API_KEY]' \
-H 'Content-Type: application/json' \
--data-binary '{"postBody":"access_token=[FACEBOOK_ACCESS_TOKEN]&providerId=[facebook.com]","requestUri":"[http://localhost]","returnIdpCredential":true,"returnSecureToken":true}'
这将返回火力地堡ID令牌和刷新令牌:
{
"idToken": "[ID_TOKEN]",
"refreshToken": "[REFRESH_TOKEN]",
...
}
这是你所需要的火力地堡验证会话。
为了构建用户,呼叫与该ID令牌以下API:
curl 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=[API_KEY]' \
-H 'Content-Type: application/json' --data-binary '{"idToken":"[FIREBASE_ID_TOKEN]"}'
这将返回用户和数据相关联:
{
"kind": "identitytoolkit#GetAccountInfoResponse",
"users": [
{
"localId": "ZY1rJK0...",
"email": "[email protected]",
"emailVerified": false,
"displayName": "John Doe",
"providerUserInfo": [
{
"providerId": "password",
"displayName": "John Doe",
"photoUrl": "http://localhost:8080/img1234567890/photo.png",
"federatedId": "[email protected]",
"email": "[email protected]",
"rawId": "[email protected]",
"screenName": "[email protected]"
}
],
"photoUrl": "https://lh5.googleusercontent.com/.../photo.jpg",
"passwordHash": "...",
"passwordUpdatedAt": 1.484124177E12,
"validSince": "1484124177",
"disabled": false,
"lastLoginAt": "1484628946000",
"createdAt": "1484124142000",
"customAuth": false
}
]
}
要刷新ID令牌到期后,使用返回的刷新令牌: 使用REST API:
curl 'https://securetoken.googleapis.com/v1/token?key=[API_KEY]' \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data 'grant_type=refresh_token&refresh_token=[REFRESH_TOKEN]'
这将返回一个新的ID令牌和刷新令牌: var firebase = require('firebase');
您发送来自客户端的FB访问令牌的HTTP端点和符号:
{
"expires_in": "3600",
"token_type": "Bearer",
"refresh_token": "[REFRESH_TOKEN]",
"id_token": "[ID_TOKEN]",
"user_id": "tRcfmLH7o2XrNELi...",
"project_id": "1234567890"
}
要在后端与客户端库使用-in:
var cred = firebase.auth.FacebookAuthProvider.credential(fbAccessToken);
firebase.auth().signInWithCredential(cred).then(function(user) {
// User is obtained here.
// To get refresh token:
// user.refreshToken
// To get ID token:
return user.getIdToken().then(function(idToken) {
// ...
})
}).catch(function(error) {
});
感谢您的回答。你能否提供更多细节?我们不想在前端客户端上使用任何Firebase库。是否可以通过Facebook访问令牌(通过客户端上的FB SDK检索)并在Firebase云功能上完成其他登录过程? – Ayyappa
虽然我不推荐它,但可以这样做。老实说,这非常简单。我将添加HTTP API来调用我的原始答案。 – bojeil