Using mail and password to authenticate via the REST API [Firebase]
Asked Answered
R

5

54

I was wondering whether it is possible to actually authenticate to the Firebase REST API withouth using the custom authentication?

I've worked with Firebase now for some time and I'm currently thinking about migrating a backend of mine to Firebase. The app that uses the backend currently uses a REST API and does not need realtime data at all. Thus I'd like to use only the REST API and not the full Android framework on the clients.

Is it possible to get an auth token using the mail & password authentication of Firebase via HTTP-requests?

In the old docs I've only found a solution with custom login and in the new docs you seem to need a Google Service Account.

Any help or advice appreciated.

Roo answered 19/5, 2016 at 12:6 Comment(2)
Neither the legacy firebase.com nor the new firebase.google.com SDKs allow you to mint a token via its REST API. You'll have to set up a server/endpoint that mints the token, for example with one of the supported libraries: firebase.google.com/docs/auth/server#create_a_custom_token.Prink
@FrankvanPuffelen Hello Frank, thanks for taking the time to answer. As nloewen stated below and I thought myself you surely use HTTP request inside your SDKs aswell. So there has to be some way, even if it isn't officially supported. But I'll take a look at the custom token generation aswell, thank you.Roo
A
80

Update: Firebase REST authentication is now documented!

View the documentation


Firebase REST authentication

I figured out how to perform email and password authentication for Firebase by examining the requests sent by the Javascript API.

These APIs are undocumented and unsupported


Firebase 3

Firebase 3 authentication is an updated and renamed version of the Google Identity Toolkit. The old documentation is not fully accurate, but may be useful and can be found here: https://developers.google.com/identity/toolkit/web/reference/

Firebase 3 requires all requests to have Content-Type: application/json in the header

API Key

Firebase 3 requires an API key to be attached to all authentication requests. You can find the API key for your database by visiting the Firebase project overview and clicking on "Add Firebase to your web app". You should see a window with code like the following:

<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js">    </script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "<my-firebase-api-key>",
    authDomain: "my-firebase.firebaseapp.com",
    databaseURL: "https://my-firebase.firebaseio.com",
    storageBucket: "my-firebase.appspot.com",
  };
  firebase.initializeApp(config);
</script>

Copy the apiKey value and save it for later.

Registration

Method: POST

URL: https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=<my-firebase-api-key>

Payload:

{
    email: "<email>",
    password: "<password>",
    returnSecureToken: true
}

Response:

{
    "kind": "identitytoolkit#SignupNewUserResponse",
    "localId": "<firebase-user-id>", // Use this to uniquely identify users
    "email": "<email>",
    "displayName": "",
    "idToken": "<provider-id-token>", // Use this as the auth token in database requests
    "registered": true,
    "refreshToken": "<refresh-token>",
    "expiresIn": "3600"
}

Login

Method: POST

URL: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=<my-firebase-api-key>

Payload:

{
    email: "<email>",
    password: "<password>",
    returnSecureToken: true
}

Response:

{
    "kind": "identitytoolkit#VerifyPasswordResponse",
    "localId": "<firebase-user-id>", // Use this to uniquely identify users
    "email": "<email>",
    "displayName": "",
    "idToken": "<provider-id-token>", // Use this as the auth token in database requests
    "registered": true,
    "refreshToken": "<refresh-token>",
    "expiresIn": "3600"
}

Get Account Info

Method: POST

URL: https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=<my-firebase-api-key>

Payload:

{
    idToken: "<provider-id-token>"
}

Response:

{
    "kind": "identitytoolkit#GetAccountInfoResponse",
    "users": [
    {
        "localId": "<firebase-user-id>",
        "email": "<email>",
        "emailVerified": false,
        "providerUserInfo": [
        {
            "providerId": "<password>",
            "federatedId": "<email>",
            "email": "<email>",
            "rawId": "<email>"
        }],
        "passwordHash": "<hash>",
        "passwordUpdatedAt": 1.465327109E12,
        "validSince": "1465327108",
        "createdAt": "1465327108000"
    }]
}

Firebase 2

These requests return JSON data described in the Firebase docs. https://www.firebase.com/docs/web/guide/login/password.html#section-logging-in

Login

You can authenticate by sending a GET request with the following format:

https://auth.firebase.com/v2/<db_name>/auth/password?&email=<email>&password=<password>

Registration

User creation can also be performed by sending the same GET request with _method=POST as part of the query string

https://auth.firebase.com/v2/<db_name>/users?&email=<email>&password=<password>&_method=POST
Antipope answered 24/5, 2016 at 16:32 Comment(15)
Unsupported and likely to change at any time, as those are internal API endpoints.Kinelski
Even though it is unsupported this is exaclty what I need actually. Except I'd need something like this for the new version of firebase. :/Roo
@Roo I've updated my answer with information about REST authentication for Firebase 3. This isn't a complete list of authentication operations, but should get you started :) If you work out the format for other operations, please come back let us know!Antipope
Really great job. How likely is these urls to change? Why firebase doesn't document these for us?Profit
@Profit They probably won't change as that would break cause old versions of the SDK to break.Antipope
@jcrowson Firebase 3 is still working for me as of 5/11/2016Doll
I am able to get my idToken/accessToken, but I don't know how to use it to access my database. I get permission denied when I try to access <database-url>.json?access_token=<access-token>Venetis
Make sure your security rules are correct and try replacing "access_token" with "auth"Antipope
@Antipope I am trying to access my firebase db, but I get 403 permission denied. Can you have a look at my question here. I am posting in my header the token received from OAuth 2.0 server. What is the point of using Web key in this instance if already have a token from the service account? Thanks for your timeJackhammer
@Jackhammer I've posted a response to your question which I believe will solve your problem. You only need to include the API key when making authentication requests. It's not needed when accessing the database.Antipope
This is now official and documented here: firebase.google.com/docs/reference/rest/auth/…Okechuku
how does one interface with this API using account services/oauth2 access token, as in how do make administrative actions on firebase accounts without needs a the clients idTokenArawakan
Can someone answer on pricing part about this - #57391584Panama
Great answer, if only sign-out was officially documented too. Currently I see now way of signing out directly through the API.Noctilucent
I'm pretty sure the way to sign out would be to discard your access token. At some point it will expire, and not having it is just as good as invalidating it.Antipope
S
4

From Firebase Guide Authenticate with Firebase on Websites Using a Custom Authentication System (Please see https://firebase.google.com/docs/auth/web/custom-auth)

You can integrate Firebase Authentication with a custom authentication system by modifying your authentication server to produce custom signed tokens when a user successfully signs in. Your app receives this token and uses it to authenticate with Firebase.

Here's the key idea:

1) Add Firebase to your Web Project and use Firebase REST JavaScript SDK for Authentication, and access Storage / Realtime Database with Firebase.

  // TODO: Replace with your project's customized code snippet
  <script src="https://www.gstatic.com/firebasejs/3.0.2/firebase.js"></script>
  <script>
    // Initialize Firebase
    var config = {
      apiKey: '<your-api-key>',
      authDomain: '<your-auth-domain>',
      databaseURL: '<your-database-url>',
      storageBucket: '<your-storage-bucket>'
    };
    firebase.initializeApp(config);
  </script>

2) You app users sign in to your authentication server using their username and password. Your server checks the credentials and returns a custom token if they are valid.

3) After you receive the custom token from your authentication server, pass it to signInWithCustomToken to sign in the user

firebase.auth().signInWithCustomToken(token).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});
Screwed answered 27/5, 2016 at 6:41 Comment(0)
A
2

If you try through REST API than you have to do all operation in your Apllication .

Just grab the json data and checked your authenticate or not .

use retrofit Get method and just grab all data from your firebase app.

this is my post Rerofit + Firebase which i was posted for the beginner to understand connection of firebase and Retrofit.

OR

Please go through this links it gonna help you .....................

REST auth

User Authnitication

Example

enjoy coding.......

Awful answered 21/5, 2016 at 19:9 Comment(1)
I am trying to access Firebase db from my web app through https post request, but I get 403 access denied. Can you have a look at my question as none of the answers above works for me. I use swift + vapor framework.Jackhammer
M
0

You need the return of a Token once you authenticate with your Email & Password, according to the documentation you can return the token of a user with getToken(opt_forceRefresh), is available at the following URL.

https://firebase.google.com/docs/reference/js/firebase.User#getToken

Monetta answered 21/5, 2016 at 18:39 Comment(0)
I
0

I believe you can do one of the following:

  • Connect your web app to Firebase, your REST API will handle the authentication by receiving the user credentials, then authenticating with the Firebase through the web APIs Password Authentication

  • Use the Firebase server SDK to generate custom authentication tokens, the token will be a JSON Web Token (JWT).

There are also projects on GitHub for generating Firebase tokens:

Ingeminate answered 28/5, 2016 at 11:7 Comment(1)
Yeah, Im trying both ways and neither works from python. Do you know any python examples using either method? The link you posted is the token generator itself, but I want to see an example of how it is used in python. ThanksApolitical

© 2022 - 2024 — McMap. All rights reserved.