Not sure why this code isn't running. Copied all required snippets from Firebase and my button is firing. Any ideas as to what could be going wrong? Github is making me write more stuff in here so here.
Thanks!
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Auth</title>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script>
</head>
<body>
<button onclick="googleAuth()">SIGN UP</button>
<script>
var provider = new firebase.auth.GoogleAuthProvider();
var googleAuth = function() {
console.log(firebase);
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;
// ...
});
};
</script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBeJIaAAD5-vK0kBDTRH6Y6_1ByVE3erJY",
authDomain: "fir-chat-d28be.firebaseapp.com",
databaseURL: "https://fir-chat-d28be.firebaseio.com",
storageBucket: "fir-chat-d28be.appspot.com",
};
firebase.initializeApp(config);
</script>
</body>
You must follow the instructions in log:
The current domain is not authorized for OAuth operations. This will prevent signInWithPopup, signInWithRedirect, linkWithPopup and linkWithRedirect from working. Add your domain to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.
See how it says signInWithPopup will not work without your domain added in Firebase console
Follow the instructions I listed when I was having a similar error, this will enable you to solve the oAuth issue.
Firebase GAS webapp Google popup disappears
Your code looks good, but if you run that as an HTML file, you'll get an error similar to "This operation is not supported in the environment this application is running on. "location.protocol" must be http or https".
I'd suggest you to take advantage of Firebase Hosting feature. You can easily deploy and host your app's static assets like HTML, CSS, JavaScript, etc.. Moreover, it's free of charge.
in my experience ( just for advice ), dont use firebase auth with provider like google or facebook. use email and password auth for better security. you can use FirebaseUi, verry easy to understand, and you can copy-paste if you like. if you use Google auth, every user who have google account can access your apps, read, write, delete, and update. except, you have better experience with Firebase Rules.
Related
Hello! I am OCD about security for my app and was wondering how to properly login/signup a user with the Google auth provider.
I have a client ID and secret for that client ID - from Google Credentials - for my app. I know not to put the secret in the client.
The code below works perfectly but I'm unsure if it's safe to generate an id_token for a user directly without any server code because of this doc from Expo Go:
Notice it says "be sure that you don't directly request the access token for the user". I don't know what this means exactly.
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
clientId:
"my-client-id-goes-here.google.apps.com",
});
React.useEffect(() => {
if (response?.type === "success") {
const { id_token } = response.params;
const credential = new GoogleFirebase.GoogleAuthProvider.credential(
id_token
);
}
}, [response]);
Any ideas on how to execute this securely to make sure a user can't change the URL redirect parameters from Google or anything? I'm just not 100% on what I'm doing here.
Use an .env file to store your sensitive information. For example in your .env file put
CLIENTID="my-client-id-goes-here.google.apps.com"
Then call it like you did above:
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
clientId:
process.env.CLIENTID,
});
I am trying to use Facebook login using Firebase authentication. I have followed whole documentation. Lastly whenever I click the login button it gives an error saying:
Cannot pass a read permission (email) to a request for publish authorization
The line on which it is showing error is:
LoginManager.getInstance().logInWithPublishPermissions(LoginActivity.this,Arrays.asList("email", "public_profile"));
Can someone explain me what I am doing wrong? I have looked other answers also but no help from there.
Use logInWithReadPermissions instead of logInWithPublishPermissions. The error message is very clear about that, you are trying to request read permissions with a function that is being used for publish permissions.
.getInstance().logInWithPublishPermissions is not Firebase Authentication. Signin via federated providers such as Facebook is available via the Firebase JavaScript (web) SDK. See Authenticate Using Facebook Login with JavaScript for details.
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Facebook Access Token. You can use it to access the Facebook 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;
// ...
});
First of all, I am using nodejs for the backend. I use firebase hosting and firebase functions to deploy an express() app.
What I am trying to achieve is to make an admin website, which is connected to Firebase. so I have a route /admin/ like this:
adminApp.get("/", (request, response) => {
return response.redirect("/admin/login");
});
Here I basically want to check if a current user is logged in - or not.
I know firebase supports client side authentication using:
firebase.auth().onAuthStateChanged(user => {
if (user) {
} else {
}
});
And using
function login() {
var userEmail = document.getElementById("email").value;
var userPass = document.getElementById("password").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (error) {
document.getElementById('loginError').innerHTML = `Error signing in to firebase`;
}
});
}
However image this case:
Someone (not an admin) is visiting /admin/some_secret_website/ which he obviously does not have access to.
If I rely on client side authentication, it first loads the entire website and the scripts and then notices - hey I am not authenticated, let me redirect to /login. By then however anyone knows the source code of an admin page.
I'd rather have something like:
adminApp.get("/admin/some_secret_website", (request, response) => {
if (request.user) {
// user is authenticated we can check if the user is an admin and give access to the admin page
}
});
I know that you can get the user's token and validate that token using the AdminSDK, but the token must be send by the client code, meaning the website was already loaded.
I came across Authorized HTTPS Endpoint by firebase, but it only allows a middleware when using a bearer token.
Does anybody know how I can maintain a server side user object to not even return admin html to the browser but only allow access to admins?
Like Doug indicated, the way your admin website/webapp would function with Firebase Cloud Functions (which is effectively a Nodejs server) is that you get the request, then use the headers token to authenticate them against Firebase Auth. See this answer for a code snippet on this.
In your case, I'm thinking you would create a custom claim for an "administrator" group and use that to determine whether to send a pug templated page as a response upon authentication. As far as Authorization, your db rules will determine what said user can CRUD.
My site is just one page with a form. I don't have any user auth functionality . Can I still use client side firebase integration without passing through a server side code in a secure way? If yes how can I secure the details for my firebase connection ?
You can use the new anonymous auth functionality provided by Firebase Simple Login: https://www.firebase.com/docs/security/simple-login-anonymous.html
With this mechanism, you can have users of your website authenticate to Firebase anonymously (they don't need to enter any login credentials), but you can still protect reads and writes to your Firebase using regular security rules.
Yes.
Just add these tags to you page:
<script type="text/javascript" src="https://cdn.firebase.com/v0/firebase.js"></script>
<script type="text/javascript" src="https://cdn.firebase.com/v0/firebase-simple-login.js"></script>
Then write this code:
var chatRef = new Firebase('https://YOUR-APP.firebaseIO.com');
var auth = new FirebaseSimpleLogin(chatRef, function(error, user) {
if (error) {
// an error occurred while attempting login
console.log(error);
} else if (user) {
// user authenticated with Firebase
console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
} else {
// user is logged out
}
});
And when your user clicks the login button, call
// attempt to log the user in with your preferred authentication provider
auth.login('github (or twitter, or what you want)');
As explained here and demonstrated here.
I am using firebase facebook simple login.
Is there any way I can use it conjunction with facebook js graph api?
Let say, calling FB.api('xxx', function(){}) ?
Facebook via Firebase Simple Login returns the Facebook access token as part of the payload. You could then use this directly with the Facebook Graph API and their JavaScript SDK:
var ref = new Firebase(URL);
var auth = new FirebaseSimpleLogin(ref, function(error, user) {
if (user) {
var facebookToken = user.accessToken; // <<-- here it is
}
});
// Note: Attach this to a click event to permit the pop-up to be shown
auth.login('facebook');
As you noted, Singly is another great approach that abstracts some of the effort of talking to Facebook, but shouldn't be necessary if your use case is fairly straightforward.
UPDATE
Firebase Simple Login now supports authenticating a user with an existing Facebook access token, meaning that you can easily use the Facebook JS SDK in combination with Firebase Simple Login without asking your users to authenticate twice.
For example, once you have a valid Facebook access token using the Facebook JS SDK:
var ref = new Firebase(...);
var auth = new FirebaseSimpleLogin(ref, function(error, user) { ... });
auth.login('facebook', { access_token: '<ACCESS_TOKEN>' });
See the access_token option at https://www.firebase.com/docs/security/simple-login-facebook.html for more information.