Firebase ApplicationDefaultCredentials doesn't

2019-09-12 00:08发布

I'm following the instructions on: https://cloud.google.com/solutions/using-firebase-real-time-events-app-engine

I'm trying to get my dev_appserver to make credentialed requests to a firebase database. This works after I've deployed, but not locally.

I've run gcloud auth application-default login

and have set up my credentials as follows:

try:
    from functools import lru_cache
except ImportError:
    from functools32 import lru_cache

import json

import httplib2
from oauth2client.client import GoogleCredentials

_FIREBASE_SCOPES = [
    'https://www.googleapis.com/auth/firebase.database',
    'https://www.googleapis.com/auth/userinfo.email']


# Memoize the authorized http, to avoid fetching new access tokens
@lru_cache()
def _get_http():
    """Provides an authed http object."""
    http = httplib2.Http()
    # Use application default credentials to make the Firebase calls
    # https://firebase.google.com/docs/reference/rest/database/user-auth
    creds = GoogleCredentials.get_application_default().create_scoped(
        _FIREBASE_SCOPES)
    creds.authorize(http)
    return http


def firebase_put(path, value=None):
    """Writes data to Firebase.
    An HTTP PUT writes an entire object at the given database path. Updates to
    fields cannot be performed without overwriting the entire object
    Args:
        path - the url to the Firebase object to write.
        value - a json string.
    """
    response, content = _get_http().request(path, method='PUT', body=value)
    return json.loads(content)

when calling firebase_put() I get

{
  "error" : "Permission denied."
}

Strangely it just appears to be firebase that is having problems. I am able to successfully make cloud speech requests using ApplicationDefaultCredentials from dev_appserver.

I have verified that the credentials are added to the headers.

Header {
  Key: "user-agent"
  Value: "Python-httplib2/0.9.2 (gzip)"
}
Header {
  Key: "accept-encoding"
  Value: "gzip, deflate"
}
Header {
  Key: "authorization"
  Value: "Bearer REDACTED_FOR_PRIVACY"
}
Payload: "{\"sender\": \"12314\", \"timestamp\": 1478368765.042335, \"message\": \"asdf\"}"
FollowRedirects: false
Deadline: 5
MustValidateServerCertificate: true

What am I doing wrong?

1条回答
小情绪 Triste *
2楼-- · 2019-09-12 00:17

Thanks @atimothee for the essential cue.

Turns out the default scopes used by gcloud auth aplication-default login don't include userinfo.email or firebase.database. Including them manually fixed the problem.

gcloud auth application-default login --scopes=https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/firebase.database
查看更多
登录 后发表回答