我正在尝试从经过身份验证的用户(使用Firebase身份验证)检索Google Access令牌以访问Google REST API,例如YouTube Data API .
我已经在Firebase-UI for Android - Auth库的帮助下成功地在我的应用中集成了Google登录 . 从 FirebaseUser.getToken()
方法检索的令牌不是REST API的有效Google Access令牌 .
user.getToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(@NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
// 'token' is not a Google Access Token
}
}
});
在Google Sign-In for Web guide中,可以通过调用 var token = result.credential.accessToken;
来获取访问令牌,但我在Android中找不到类似的方法 .
有什么输入?如果我没有提供足够的信息,请在这里发表评论 . 谢谢 :)
3 回答
您的方式将为您提供firebase id令牌,请参阅here .
您将在firebase中遇到三种类型的令牌:
用户登录Firebase应用时由Firebase创建 . 这些令牌是签名的JWT,可以安全地识别Firebase项目中的用户 . 这些令牌包含用户的基本配置文件信息,包括用户的ID字符串,这是Firebase项目所特有的 . 由于可以验证ID令牌的完整性,因此您可以将它们发送到后端服务器以识别当前登录的用户 .
由联合身份提供商(如Google和Facebook)创建 . 这些令牌可以具有不同的格式,但通常是OAuth 2.0访问令牌 . Firebase应用使用这些令牌来验证用户是否已成功通过身份提供商进行身份验证,然后将其转换为Firebase服务可用的凭据 .
由您的自定义身份验证系统创建,允许用户使用您的身份验证系统登录Firebase应用 . 自定义令牌是使用服务帐户的私钥签名的JWT . Firebase应用程序使用这些令牌非常类似于使用联合身份提供程序返回的令牌 .
现在,你得到的是firebase Id令牌,你需要的是身份提供者令牌 .
它很容易获得身份提供者令牌,它只是您显示的步骤之前的一步 .
因此,我们使用firebase登录谷歌的方式是here .
我将在下面添加完整的代码,在UI中显示一个按钮,点击该按钮,将用户登录到Google帐户 . 然后我将获得google访问令牌,然后将其发送到firebase,然后将其转换为firebase令牌ID .
我假设您已经为谷歌登录配置了Android应用程序,如果没有,您可以进入详细信息here .
(To cut things short, just look at Step 5 below, if you have done setup already.)
Code :
所以,你的答案在于第5步,就在你对firebase进行身份验证之前,以及在google登录后进行身份验证之后 .
希望能帮助到你 !
UPDATE :
Its important that in Step 1, you request for token Id, otherwise in Step 5, you will get null token id. For more see here. I have updated Step 1.
UPDATE :
As per discussion, the retrieved token was JWT token as written here. And what we need is google access token. Below code uses the JWT token to fire at OAuth backend and retrieve this access token :
(注意:我使用过okhttp 2.6.0版,其他版本可能有不同的方法)
Code :
以下是根据需要具有访问令牌的输出:
希望现在有所帮助!
试试GoogleAuthUtil.getToken,其中scope就像"oauth2:scope1 scope2 scope3"
我正在关注@vovkas解决方案,并希望通过上次更新
11.6.0
告诉您,您可以更轻松地获得所需的Account
,因此您可以随时随地重复使用方便的花花公子AsyncTask
中的所有内容:关键是使用
GoogleSignIn.getLastSignedInAccount(context)
.