最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add Google authentication to Firebase Real Time Database - Stack Overflow

programmeradmin5浏览0评论

I'm using the Firebase Real Time Database and I need to add user authentication to it. Users can only login with Google as a provider.

Current database mode:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

New mode should be like this:

// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

What should I use to authenticate in my case? userID, Google providerID or a token like described here?

This is the function without authentication to store data:

 createMeetup ({mit, getters}, payload) {
      console.log('index.js -> createMeetup')
      const meetup = {
        title: payload.title,
      }
      let imageUrl
      let key
      firebase.database().ref('meetups').push(meetup)
        .then((data) => {
          key = data.key
          return key
        })
        .then(() => {
          mit('createMeetup', {
            ...meetup,
            imageUrl: imageUrl,
            id: key
          })
        })
        .catch((error) => {
          console.log(error)
        })
    },

I'm using the Firebase Real Time Database and I need to add user authentication to it. Users can only login with Google as a provider.

Current database mode:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

New mode should be like this:

// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

What should I use to authenticate in my case? userID, Google providerID or a token like described here?

This is the function without authentication to store data:

 createMeetup ({mit, getters}, payload) {
      console.log('index.js -> createMeetup')
      const meetup = {
        title: payload.title,
      }
      let imageUrl
      let key
      firebase.database().ref('meetups').push(meetup)
        .then((data) => {
          key = data.key
          return key
        })
        .then(() => {
          mit('createMeetup', {
            ...meetup,
            imageUrl: imageUrl,
            id: key
          })
        })
        .catch((error) => {
          console.log(error)
        })
    },
Share Improve this question asked Dec 3, 2018 at 19:09 TomTom 6,00421 gold badges85 silver badges134 bronze badges 1
  • You should use google plus to auth, and automatically when the user tries to read or write data to the node the UID is detected – Kisinga Commented Dec 3, 2018 at 19:47
Add a ment  | 

4 Answers 4

Reset to default 3

For your use case it seems like you need to sort out a few steps. I'm guessing your application can already connect/use Firebase, but these are essentially it:

Step 1 - Connecting

Connect to Firebase using your API key/config as per usual, should look something like the following.

firebase.initializeApp(config)

See also: https://firebase.google./docs/web/setup

You probably already have this somewhere. This does not change, but if you would apply the rules as described your users would not be able to use Firebase after just connecting.

Step 2 - Authenticating

This is basically telling Firebase who is connected. This must be done with a token/method Firebase can verify. Using a Google ID is the most mon method.

With an existing Google ID / user login

// Initialize a generate OAuth provider with a `google.` providerId.
var provider = new firebase.auth.OAuthProvider('google.');
var credential = provider.credential(googleUser.getAuthResponse().id_token);
firebase.auth().signInWithCredential(credential)

See also: https://firebase.google./docs/reference/js/firebase.auth.OAuthProvider#credential

Or make Firebase SDK do the login flow

var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
  // This gives you a Google Access Token. You can use it to access the Google API.
  var token = result.credential.accessToken;
  // The signed-in user info.
  var user = result.user;
  // ...
})

See also: https://firebase.google./docs/auth/web/google-signin

This last option is preferred / suggested by the documentation you referenced.

If, as you described, users can already login with Google to your app for other functionalities then you should already have a login flow somewhere. Depending on your situation it might be advisable to let the Firebase SDK / library take over this process for simplicity in your application.

Step 3 - Using the database

Lastly, after authenticating users and applying the rules you suggested you will need to also make sure the paths you write to are within those accessible by the current user. You can put this in a simple function to make it easier.

const getUserRef = (ref) => {
  const user = firebase.auth().currentUser;
  return firebase.database().ref(`/users/${user.uid}/${ref}/`);
}

You should of course not be retrieving the current user every time you want to get a database reference, but I think this clearly illustrates the steps that need to be taken.

You can allow users to login/auth using multiple methods. Then you can merge them together to a single account as described here:

https://firebase.google./docs/auth/web/account-linking

So really it boils down to two options:

  1. Allow users to login with multiple methods such as Facebook, Google, Github, basic username/password, etc.
  2. Or allow only a single login method such as Google only.

Whichever options you pick will help you decide which ID to use.

The auth rules in your question are only stating that the users can read/write their own (presumably) user data.

I assume that you are rather looking for a solution to authorize the user to create meetup data and you should crerate rules similar to this:

These rules allow any user that is logged in to create meetups

{
  "rules": {
    "meetups": {
      "$meetupId": {
        ".read": "auth.uid != null",
        ".write": "auth.uid != null"
      }
    }
  }
}

Your code-snippet that pushes new meetup data to the database will automatically try and succeed or fail depending on whether the user was logged in or not. You don't need to specifically tell Firebase in which way the user was logged in. Firebase SDK will take care of the authentication for you.

But if you do want to provide different mechanisms depending on which login type that the user is authenticated with, you can check it in the rules. For example if you want to make sure that the user is not just "anonymously" logged in.

See the documentation: https://firebase.google./docs/database/security/user-security#section-variable

the documentation has you covered there: Authenticate Using Google Sign-In with JavaScript.

You can let your users authenticate with Firebase using their Google Accounts by integrating Google Sign-In into your app. You can integrate Google Sign-In either by using the Firebase SDK to carry out the sign-in flow, or by carrying out the Google Sign-In flow manually and passing the resulting ID token to Firebase.

Before you begin:

  • Add Firebase to your JavaScript project.
  • Enable Google Sign-In in the Firebase console:
  • In the Firebase console, open the Auth section.
  • On the Sign in method tab, enable the Google sign-in method and click Save.
  • Handle the sign-in flow with the Firebase SDK If you are building a web app, the easiest way to authenticate your users with Firebase using their Google Accounts is to handle the sign-in flow with the Firebase JavaScript SDK. (If you want to authenticate a user in Node.js or other non-browser environment, you must handle the sign-in flow manually.)

To handle the sign-in flow with the Firebase JavaScript SDK, follow these steps:

Create an instance of the Google provider object:

var provider = new firebase.auth.GoogleAuthProvider();

Optional: Specify additional OAuth 2.0 scopes that you want to request from the authentication provider. To add a scope, call addScope().

For example:

provider.addScope('https://www.googleapis./auth/contacts.readonly');

See the authentication provider documentation. Optional: To localize the provider's OAuth flow to the user's preferred language without explicitly passing the relevant custom OAuth parameters, update the language code on the Auth instance before starting the OAuth flow.

For example:

firebase.auth().languageCode = 'pt';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

Optional: Specify additional custom OAuth provider parameters that you want to send with the OAuth request. To add a custom parameter, call setCustomParameters on the initialized provider with an object containing the key as specified by the OAuth provider documentation and the corresponding value.

For example:

provider.setCustomParameters({
    'login_hint': '[email protected]'
});

Reserved required OAuth parameters are not allowed and will be ignored. See the authentication provider reference for more details. Authenticate with Firebase using the Google provider object. You can prompt your users to sign in with their Google Accounts either by opening a pop-up window or by redirecting to the sign-in page. The redirect method is preferred on mobile devices.

To sign in with a pop-up window, call signInWithPopup:

firebase.auth().signInWithPopup(provider).then(function(result) {

    // This gives you a Google Access Token. You can use it to access the Google API.
    var token = result.credential.accessToken;
    // The signed-in user info.
    var user = result.user;
    // ...

}).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // The email of the user's account used.
    var email = error.email;
    // The firebase.auth.AuthCredential type that was used.
    var credential = error.credential;
    // ...
});

Also notice that you can retrieve the Google provider's OAuth token which can be used to fetch additional data using the Google APIs. This is also where you can catch and handle errors. For a list of error codes have a look at the Auth Reference Docs.

To sign in by redirecting to the sign-in page, call signInWithRedirect:

firebase.auth().signInWithRedirect(provider);

Then, you can also retrieve the Google provider's OAuth token by calling getRedirectResult() when your page loads:

firebase.auth().getRedirectResult().then(function(result) {
    if (result.credential) {
        // This gives you a Google Access Token. You can use it to access the Google API.
        var token = result.credential.accessToken;
        // ...
    }

    // The signed-in user info.
    var user = result.user;
}).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // The email of the user's account used.
    var email = error.email;
    // The firebase.auth.AuthCredential type that was used.
    var credential = error.credential;
    // ...
});
发布评论

评论列表(0)

  1. 暂无评论