首页 > 解决方案 > 通过 Firebase rest api 使用 OAuth2 登录被拒绝

问题描述

我正在尝试通过 Google Apps 脚本中的 Firebase REST API 使用 OAuth2 登录用户。我正在使用apps-script-oauth2库并使用service.getAccessToken()请参阅 getAccessToken 文档)检索了访问令牌。

但是,当我使用以下代码发布到身份验证端点时:

    var oAuthService= getOAuthService();
    const createUserWithOAuthUrl = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyAssertion?key=' + <API_KEY>
    const accessToken = oAuthService.getAccessToken()
    Logger.log(accessToken)
    const requestUri = 'https://script.google.com/macros/d/' + SCRIPT_ID + '/usercallback'
    const payload = JSON.stringify({"postBody": "access_token=" + accessToken + "&providerId=google.com","requestUri":requestUri,"returnIdpCredential":true,"returnSecureToken":true})
    Logger.log(payload)
    const result = UrlFetchApp.fetch(createUserWithOAuthUrl, {
        method: 'post',
        contentType: 'application/json',
        muteHttpExceptions: true,
//        headers: {
//          Authorization: 'Bearer ' + accessToken
//        },
        payload : payload
    });

我收到此错误:

"error": {
    "code": 400,
    "message": "INVALID_IDP_RESPONSE : Failed to fetch resource from https://www.googleapis.com/oauth2/v1/userinfo, http status: 401, http response: {\n  \"error\": {\n    \"code\": 401,\n    \"message\": \"Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.\",\n    \"status\": \"UNAUTHENTICATED\"\n  }\n}\n",

当我完成帐户选择/范围审查流程并获得授权提示时,OAuth 流程似乎进展顺利。

我已经关注了firebase rest auth api docs,看起来我这样做的方式是正确的,所以我很困惑为什么它被拒绝了。有什么想法吗?有什么方法可以测试我的 access_token 的有效性吗?我已经控制台记录了它,它看起来确实像令牌。

标签: firebaseoauth-2.0firebase-authentication

解决方案


好的,所以我只是想通了,它与范围有关。

基本上,在使用 OAuth 过程的 firebase 登录过程中,会自动调用https://www.googleapis.com/oauth2/v1/userinfoapi。这需要以下范围:

https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile

我想 firebase 想要将特定的用户详细信息添加到用户帐户中。不知道为什么它抱怨令牌而不是范围,肯定把我扔在那里!


推荐阅读