0

When using the Firebase Admin SDK in Go, I'm facing an issue where I can't authenticate on the Realtime Database.

Here's how I start the database connection:

option := option.WithTokenSource(tokenSource)
app, err := firebase.NewApp(context.Background(), &firebase.Config{
    DatabaseURL: "https://databaseName.europe-west1.firebasedatabase.app/",
    ProjectID:   "projectId",
}, option)
client, err := app.Database(context.Background())

The tokenSource is a custom TokenSource that return a ReuseTokenSource. I've override the Token() method to fit my needs, which is: get an IdToken from a custom endpoint at first and then when the IdToken is expired, refresh it from the securetoken.googleapis.com endpoint.

But with this method, whenever I try to access my Realtime database, I get the following error:

http error status: 401; reason: Unauthorized request.

Even if the Rules for the Database are fully open (read/write=true).

The Token being used is correct too as I can use it in a HTTP request, the only tweak is that I have to use ?auth=IDTOKEN instead of ?access_token=TOKEN (see here)

TLDR: How can I use an IdToken inside the Go Admin SDK to authenticate the service to the Realtime Database. (Just adding that I can authenticate the service on the Firestore Database with the same method and token).

Thank you !

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Martichou
  • 123
  • 1
  • 10

1 Answers1

2

The Admin SDK authenticates with backend services via OAuth2 (by passing an Authorization header with an OAuth2 bearer token). So you must use a TokenSource that produces OAuth2 tokens. ID tokens are generally only used for client-side auth. Here's an example that I've used in the past:

// jsonKeyBytes contains the bytes from a service account json file.
conf, err := google.JWTConfigFromJSON(jsonKeyBytes)

ts := conf.TokenSource(ctx)
firebase.NewApp(ctx, nil, option.WithTokenSource(ts))

However, typically you would directly initialize the Admin SDK with a service account or Google Application Default Credentials, in which case you don't have to do any of this.

Hiranya Jayathilaka
  • 7,180
  • 1
  • 23
  • 34