Showing posts with label Admin SDK. Show all posts
Showing posts with label Admin SDK. Show all posts

Wednesday, 30 August 2017

Introducing Firebase Admin SDK for Go

Hiranya Jayathilaka
Hiranya Jayathilaka
Software Engineer

The Firebase Admin SDK for Go is now generally available. This is the fourth programming language to join our growing family of Admin SDKs, which already includes support for Java, Python and Node.js. Firebase Admin SDKs enable application developers to programmatically access Firebase services from trusted environments. They complement the Firebase client SDKs, which enable end users to access Firebase from their web browsers and mobile devices. The initial release of the Firebase Admin SDK for Go comes with some Firebase Authentication features: custom token minting and ID token verification.

Initializing the Admin SDK for Go

Similar to the other Firebase Admin SDKs, the Go Admin SDK can be initialized with a variety of authentication credentials and client options. The following code snippet shows how to initialize the SDK using a service account credential obtained from the Firebase console or the Google Cloud console:

import (
"golang.org/x/net/context"

firebase "firebase.google.com/go"
"google.golang.org/api/option"
)

opt := option.WithCredentialsFile("path/to/key.json")
app, err := firebase.NewApp(context.Background(), nil, opt)

If you are running your code on Google infrastructure, such as Google App Engine or Google Compute Engine, the SDK can auto-discover application default credentials from the environment. In this case you do not have to explicitly specify any credentials when initializing the Go Admin SDK:

import (
"golang.org/x/net/context"

firebase "firebase.google.com/go"
)

app, err := firebase.NewApp(context.Background(), nil)

Minting Custom Tokens and Verifying ID Tokens

The initial release of the Firebase Admin SDK for Go comes with support for minting custom tokens and verifying Firebase ID tokens. The custom token minting allows you to authenticate users using your own user store or authentication mechanism:

client, err := app.Auth()
if err != nil {
return err
}

claims := map[string]interface{}{
"premium": true,
"package": "gold",
}
token, err := client.CustomToken("some-uid", claims)

The resulting custom token can be sent to a client device, where it can be used to initiate an authentication flow using a Firebase client SDK. On the other hand, the ID token verification facilitates securely identifying the currently signed in user on your server:

client, err := app.Auth()
if err != nil {
return err
}

decoded, err := client.VerifyIDToken(idToken)
uid := decoded.UID

To learn more about using the Firebase Admin SDK for Go, see our Admin SDK setup guide.

What's Next?

We plan to further expand the capabilities of the Go Admin SDK by implementing other useful APIs such as user management and Firebase Cloud Messaging. This SDK is also open source. Therefore we welcome you to browse our Github repo and get involved in the development process by reporting issues and sending pull requests. To all Golang gophers out there, happy coding with Firebase!

Share:

Thursday, 6 July 2017

Accessing Database from the Python Admin SDK

Diego Giorgini
Hiranya Jayathilaka
Software Engineer

Last April, we announcedthe general availability of the Firebase Admin SDK for Python. The initial release of this SDK supported two important features related to Firebase Authentication: minting custom tokens, and verifying ID tokens. Now, we are excited to announce that database support is available in the Firebase Admin SDK for Python starting from version 2.1.0.

Due to the way it's implemented, there are several notable differences between this API and the database APIs found in our other Admin SDKs (Node.js and Java). The most prominent of these differences is the lack of support for realtime event listeners. The Python Admin SDK currently does not provide a way to add event listeners to a database reference in order to receive realtime update notifications. Instead, all data retrieval operations are provided as blocking methods. However, despite these differences there's a lot that can be achieved using this API.

The database module of the Python Admin SDK facilitates both basic data manipulation operations and advanced queries. To begin interacting with the database from a Python environment, initialize the SDK with the Realtime Database URL:

import firebase_admin
from firebase_admin import credentials

cred = credentials.Cert('path/to/serviceKey.json')
firebase_admin.initialize_app(cred, {
'databaseURL' : 'https://my-db.firebaseio.com'
})

Then obtain a database reference from the db module of the SDK. Database references expose common database operations as Python methods (get(), set(), push(), update() and delete()):

from firebase_admin import db

root = db.reference()
# Add a new user under /users.
new_user = root.child('users').push({
'name' : 'Mary Anning',
'since' : 1700
})

# Update a child attribute of the new user.
new_user.update({'since' : 1799})

# Obtain a new reference to the user, and retrieve child data.
# Result will be made available as a Python dict.
mary = db.reference('users/{0}'.format(new_user.key)).get()
print 'Name:', mary['name']
print 'Since:', mary['since']

In the Firebase Realtime Database, all data values are stored as JSON. Note how the Python Admin SDK seamlessly converts between JSON and Python's native data types.

To execute an advanced query, call one of the order_by_* methods available on the database reference. This returns a query object, which can be used to specify additional parameters. You can use this API to execute limit queries and range queries against your data, and retrieve sorted results.

from firebase_admin import db

dinos = db.reference('dinosaurs')

# Retrieve the five tallest dinosaurs in the database sorted by height.
# 'result' will be a sorted data structure (list or OrderedDict).
result = dinos.order_by_child('height').limit_to_last(5).get()

# Retrieve the 5 shortest dinosaurs that are taller than 2m.
result = dinos.order_by_child('height').start_at(2).limit_to_first(5).get()

# Retrieve the score entries whose values are between 50 and 60.
result = db.reference('scores').order_by_value() \
.start_at(50).end_at(60).get()

Take a look at the Admin SDK documentation for more information about this new API. Also check out our Github repo, and help us further improve the Admin SDK by reporting issues and contributing patches. In fact, it was your continuing feedback that motivated us to build and release this API in such a short period. Happy coding with Firebase!

Share:

Monday, 19 June 2017

Managing Users from the Firebase Admin Java SDK

Diego Giorgini
Hiranya Jayathilaka
Software Engineer


As the developer or the administrator of an app built on Firebase, you may need to perform various user management tasks. These include:

  • Provisioning new user accounts for your app
  • Updating existing user accounts
  • Manually verifying and enabling user accounts
  • Disabling or deleting user accounts
  • Querying user profile information to populate dashboards or compile reports

The Firebase Admin SDK provides a powerful API for performing these kinds of user management tasks from privileged environments. Using the Admin SDK, you can program these capabilities directly into your admin consoles, dashboards and other backend services. Unlike the Firebase client SDK, the Admin SDK is initialized with a service account credential, which grants the SDK elevated privileges necessary to perform user management operations.

This is not a brand new feature. The Firebase Admin Node.js SDK has had a user management API for a while. However, we are happy to announce that this API is now also available in our Admin Java SDK starting from version 5.1.0. This is one of the most requested features for the Admin Java SDK, and we are certain many Firebase app developers are going to find it useful.

The Java user management API closely mirrors its Node.js counterpart. Specifically, it consists of five new methods:

  • getUser()
  • getUserByEmail()
  • createUser()
  • updateUser()
  • deleteUser()

Following code snippet shows how to use some of these new methods in practice. In this example we retrieve an existing user account, and update some of its attributes:

final FirebaseAuth auth = FirebaseAuth.getInstance();
Task task = auth.getUserByEmail("editor@example.com")
.addOnSuccessListener(userRecord -> {
System.out.println("Successfully fetched user data: " + userRecord.getUid());
UpdateRequest update = userRecord.updateRequest()
.setDisabled(false) // Enable the user account
.setEmailVerified(true); // Set the email verification status
auth.updateUser(update);
})
.addOnFailureListener(e -> {
System.err.println("Error fetching user data: " + e.getMessage());
});

You can learn more about the Firebase user management API from the Admin SDK documentation. Additionally, head over to our Github repoto see how it is implemented. (Yes, it's all open source!). You can also help us further improve this API by providing us feedback and reporting issues. As always, we are open to all sorts of contributions including pull requests to our codebase. Happy coding with Firebase!

Share:

Friday, 19 May 2017

Open sourcing the Firebase SDKs

Salman Qadri
Salman Qadri
Firebase Product Manager
Originally posted on the Google Open Source Blog.

We are pleased to announce that we are taking our first steps towards open sourcing our client libraries. By making our SDKs open, we're aiming to show our commitment to greater transparency and to building a stronger developer community. To help further that goal, we'll be using GitHub as a core part of our own toolchain to enable all of you to contribute as well. As you find issues in our code, from inconsistent style to bugs, you can file issues through the standard GitHub issue tracker. You can also find our project in the Google Open Source directory. We're really looking forward to your pull requests!

What's open?

We're starting by open sourcing several products in our iOS, JavaScript, Java, Node.js and Python SDKs. We'll be looking at open sourcing our Android SDK as well. The SDKs are being licensed under Apache 2.0, the same flexible license as existing Firebase open source projects like FirebaseUI.

Let's take a look at each repo:

Firebase iOS SDK 4.0

https://github.com/firebase/firebase-ios-sdk

With the launch of the Firebase iOS 4.0 SDKs we have made several improvements to the developer experience, such as more idiomatic API names for our Swift users. By open sourcing our iOS SDKs we hope to provide an additional avenue for you to give us feedback on such features. For this first release we are open sourcing our Realtime Database, Auth, Cloud Storage and Cloud Messaging (FCM) SDKs, but going forward we intend to release more.

Because we aren't yet able to open source some of the Firebase components, the full product build process isn't available. While you can use this repo to build a FirebaseDev pod, our libraries distributed through CocoaPods will continue to be static frameworks for the time being. We are continually looking for ways to improve the developer experience for developers, however you integrate.

Our GitHub READMEprovides more details on how you build, test and contribute to our iOS SDKs.

Firebase JavaScript SDK 4.0

https://github.com/firebase/firebase-js-sdk

We are excited to announce that we are open sourcing our Realtime Database, Cloud Storage and Cloud Messaging (FCM) SDKs for JavaScript. We'll have a couple of improvements hot on the heels of this initial release, including open sourcing Firebase Authentication. We are also in the process of releasing the source maps for our components, which we expect would really improve the debuggability of your app.

Our GitHub repoincludes instructions on how you can build, test and contribute.

Firebase Admin SDKs

Node.js: https://github.com/firebase/firebase-admin-node

Java: https://github.com/firebase/firebase-admin-java

Python: https://github.com/firebase/firebase-admin-python

We are happy to announce that all three of our Admin SDKs for accessing Firebase on privileged environments are now fully open source, including our recently-launched Python SDK. While we continue to explore supporting more languages, we encourage you to use our source as inspiration to enable Firebase for your environment. (And if you do, we'd love to hear about it!)

We're really excited to see what you do with the updated SDKs - as always reach out to us with feedback or questions in the Firebase-TalkGoogle Group, on Stack Overflow, via the Firebase Support team, or now on GitHub for SDK issues and pull requests! And to read about the other improvements to Firebase that launched at Google I/O, head over to the Firebase blog.

Share:

Wednesday, 5 April 2017

Bringing Firebase Admin To Python

Diego Giorgini
Hiranya Jayathilaka
Software Engineer


After announcing the Firebase Admin SDKs for Node.js and Java at the Firebase Dev Summit in Berlin last year, we received many feature requests to bring the platform to Python developers as well. Now, we're pleased to announce that first release of the Firebase Admin Python SDK, focusing on Firebase Auth token minting and verification. 

What are the Admin SDKs?


The Firebase Admin SDKs provide developers with programmatic, second-party auth access to Firebase services from trusted environments. Second-party here refers to the fact that the SDKs are granted elevated permissions that allow them to do more than a normal, untrusted client device can. The Admin SDKs get these elevated permissions since they are authenticated with a service account, a special Google account that can be used by applications to access Google services programmatically. The Admin SDKs are meant to complement the existing Firebase web and mobile clients which provide third-party, end-user access to Firebase services on client devices.


What is available in the Admin Python SDK?


As with the other Firebase Admin SDKs, the Python SDK can be initialized using a variety of built-in credential types. The following code shows how to authenticate the SDK using your own service account key file:
import firebase_admin
from firebase_admin import credentials

cred = credentials.Certificate("path/to/service.json")
firebase_admin.initialize_app(cred)

If you are running your code on Google infrastructure, such as Google App Engine or Google Compute Engine, the SDK can auto-discover the credential, allowing you to initialize the SDK with no arguments:
firebase_admin.initialize_app()

The Python Admin SDK contains Firebase Auth custom token minting and ID token verification. The custom token minting gives you complete control over authentication by allowing you to authenticate users or devices using your own authentication system.

uid = "some-uid"
additional_claims = {
"premiumAccount": True
}

custom_token = auth.create_custom_token(uid, additional_claims)

ID token verification allows you to securely identify the currently signed-in user on your server.

decoded_token = auth.verify_id_token(id_token)
uid = decoded_token["uid"]

The best place to start is with our Admin SDKs setup guide. The guide will walk you through how to download the SDK, generate a service account key file, and use that key file to initialize the Admin SDK.


What is coming next?

We plan to continue to build out the Admin Python SDK to include features already available in the other Admin SDKs, such as a user management API and an FCM API to send messages. We also plan to bring these token minting and verification features to even more languages. To see what APIs are available in each of the Admin SDKs, see our new feature matrix.

To all those Python developers out there, happy hacking!
Share:

Thursday, 2 February 2017

Firebase Cloud Messaging integrated into the Admin Node.js SDK

Jacob Wenger
Software Engineer
With Firebase, we've been working towards a world where developers don't have to deal with managing servers and can instead build web and mobile apps with only client-side code. However, there are times when you really do need to spin up your own server. Towards that aim, we announcedthe Firebase Admin SDKs this past November.
Today, I'm excited to share two new Admin SDK features:
  • The Node.js SDK now contains an Admin API for sending messages via Firebase Cloud Messaging (FCM).
  • The Java SDK can now be initialized from a set of built-in credentials, making it easier to use, especially on Google infrastructure.
Admin Node.js FCM API
The new Admin Node.js FCM API simplifies the process of sending messages via FCM. There is no extra setup required to use this new API as the existing credential used to authenticate the Node.js SDK handles everything on your behalf. The new API contains methods for sending messages to individual devices, device groups, topics, and conditions.
As an example, let's assume you are building an app for the upcoming Super Bowl and you want to send a notification to anyone subscribed to either the Atlanta Falcons' topic (/topics/falcons) or the New England Patriots' topic (/topics/patriots):
var admin = require("firebase-admin");

// Fetch the service account key JSON file contents
var serviceAccount = require("path/to/serviceAccountKey.json");

// Initialize the app with a service account, granting admin privileges
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});

// Define who to send the message to
var condition = "'falcons' in topics || 'patriots' in topics";

// Define the message payload
var payload = {
notification: {
title: "Super Bowl LI: Falcons vs. Patriots",
body: "Your team is Super Bowl bound! Get the inside scoop on the big game."
}
};

// Send a message to the condition with the provided payload
admin.messaging.sendToCondition(condition, payload)
.then(function(response) {
console.log("Successfully sent message! Server response:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
You can optionally provide a third option to any of the FCM methods to provide options for the message. For example, since the game is a little under a week away, let's send the message with high priority and give it a time to live of one week:
// condition and payload are the same as above

var options = {
priority: "high",
timeToLive: 60 * 60 * 24 * 7
};

admin.messaging.sendToCondition(condition, payload, options)
.then(function(response) {
console.log("Successfully sent message! Server response:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
This is just a taste of what the new Admin Node.js FCM API allows you to do. See Send Messages for more code samples and detailed documentation.
Admin Java Credential Interface
Since the launch of the Admin SDKs last November, the Node.js SDK has supported several initialization methods while the Java SDK has only allowed initialization via a service account certificate file. As of the latest Admin Java SDK release, both SDKs now provide a full credential interface with some helpful default implementations.
Upgrading to the new API is straightforward. The previous way of initializing the SDK is via the setServiceAccount() method:
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountCredentials.json");

FirebaseOptions options = new FirebaseOptions.Builder()
.setServiceAccount(serviceAccount)
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com")
.build();

FirebaseApp.initializeApp(options);
The updated way of initializing the SDK is via the setCredential() method.
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountCredentials.json");

FirebaseOptions options = new FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com")
.build();

FirebaseApp.initializeApp(options);
The Admin Java SDK now includes a credential implementation based on Google Application Default Credentials. This allows for auto-discovery of service account credentials on Google infrastructure like Google App Engine and Google Compute Engine. This means you don't need to manage service account credentials yourself. Instead, you can make use of Google Application Default Credentials to run the same exact code on your local, staging, and production environments, no configuration required.
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.applicationDefault())
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com")
.build();

FirebaseApp.initializeApp(options);
See Initialize the SDK for more code samples and detailed documentation.
What's next for the Admin SDKs?
We are continually striving to expand our first-class support for backend developers in the Firebase ecosystem. Stay tuned for more features to be added to the Firebase Admin SDKs in the future! If you'd like to see a specific feature, let us know by sending us a note through our feature request support channel.
Share:

Wednesday, 9 November 2016

Bringing Firebase To Your Server

Jacob Wenger
Software Engineer

With Firebase, we've been working towards a world where developers don't have to deal with managing servers and can instead build web and mobile apps with only client-side code. However, there are times when you really do need to spin up your own server. For example, you may want to integrate with a third-party API (such as an email or SMS service), complete a computationally expensive task, or have a need for a trusted actor. We want to make your experience on this part of your stack as simple as it is on the front-end. Towards that aim, we announced the Firebase Admin SDKs for Node.js and Java at the Firebase Dev Summit in Berlin earlier this week.

What are the Admin SDKs?

The Firebase Admin SDKs provide developers with programmatic, second-party access to Firebase services from server environments. Second-party here refers to the fact that the SDKs are granted elevated permissions that allow them to do more than a normal, untrusted client device can. The Admin SDKs get these elevated permissions since they are authenticated with a service account, a special Google account that can be used by applications to access Google services programmatically. The Admin SDKs are meant to complement the existing Firebase web and mobile clients which provide third-party, end-user access to Firebase services on client devices.

Some of this may sound familiar for those of you who have used the existing Firebase Node.js and Java SDKs. The difference is that we have now split the second-party (aka "admin") and third-party (aka "end-user") access use cases into separate SDKs instead of conflating them together. This should make it easier for beginners and experts alike to know which SDK to use and which documentation to follow. It also allows us to tailor the Admin SDKs towards server-specific use cases. A great example of this is the new user management auth API which we will go into in the next section.

What can the Admin SDKs do?

The Admin SDKs for Node.js and Java offer the following admin capabilities that already existed in the prior server SDKs:

In addition, the Node.js SDK brings some exciting new functionality:

  • Admin API for managing Firebase Auth users, including the ability to fetch user data, create new users, update user properties, and delete users. You can do all of this without a user's existing password and without worrying about rate limiting. This has been a heavily requested feature from developers for years now and we are excited to finally put it into your hands.
  • Auto-discovery of service account credentials on Google infrastructure like Google App Engine and Google Compute Engine. This means you don't need to manage service account credentials yourself. Instead, you can make use of Google Application Default Credentials to run the same exact code on your local, staging, and production environments, no configuration required.

How can I get started with the Admin SDKs?

The best place to start is with our Admin SDKs setup guide. The guide will walk you through how to download the SDK, generate a service account key file, and use that key file to initialize the Admin SDK. Thanks to our new Service Accounts panel in your Firebase Console settings, generating service account keys should be a breeze.

What's next for the Admin SDKs?

This is really just the beginning for the Admin SDKs. We plan to expand the Admin SDKs across two dimensions. Firstly, we want to provide Admin SDKs in more programming languages, allowing you to write code in the language you feel most comfortable. Secondly, we plan to integrate with more Firebase services, including adding support for services like Firebase Cloud Messaging and bringing the new user management API to Java.

Would you like us to build an Admin SDK in a particular language? Do you want the Admin SDKs to support a certain Firebase service or feature? Let us know in the comments below or by sending us a note through our feature request support channel.

We are excited to expand our first-class support for backend developers in the Firebase ecosystem. Stay tuned for more to come in the future!

Share: