Firebase security with angularfire - angularfire

I'm new to firebase and angularfire. AngularJS is client side code. Its public to anyone. What prevents a hacker from taking the following firebase reference, and using it in another app?
var peopleRef = new Firebase("https://<my-firebase>.firebaseio.com/people");
$scope.people = $firebase(peopleRef);

I think that Firebase has security rules surrounding who can do what with your data. So, I think you can specify users in your firebase that can have read/write permissions. I have never used them, but you can read about them here: https://www.firebase.com/docs/security/security-rules.html

Related

Change Password with firebase cloud functions

I have found documents (Manage Users ** Firebase Official docs) on how to change a password but not how to use a cloud function. The user.updatePassword(newPassword).then(() => { does not work for a cloud function. --> At lease that i am aware of...
My Goal if possible, is to pass the users userid and new password in a similar fashion to the above and have it change. Any examples or firebase doc's i might have missed would be great.
Cheers
Inside Cloud Function you're using the Firebase Admin SDK to access Firebase Authentication, so you can update the user through that to set their password. From that link:
getAuth()
.updateUser(uid, {
password: 'newPassword',
})

Is it okay to use Firebase Auth SDK for Mobile app authentication on the frontend? [duplicate]

The Firebase Web-App guide states I should put the given apiKey in my Html to initialize 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>
By doing so, the apiKey is exposed to every visitor.
What is the purpose of that key and is it really meant to be public?
The apiKey in this configuration snippet just identifies your Firebase project on the Google servers. It is not a security risk for someone to know it. In fact, it is necessary for them to know it, in order for them to interact with your Firebase project. This same configuration data is also included in every iOS and Android app that uses Firebase as its backend.
In that sense it is very similar to the database URL that identifies the back-end database associated with your project in the same snippet: https://<app-id>.firebaseio.com. See this question on why this is not a security risk: How to restrict Firebase data modification?, including the use of Firebase's server side security rules to ensure only authorized users can access the backend services.
If you want to learn how to secure all data access to your Firebase backend services is authorized, read up on the documentation on Firebase security rules. These rules control access to file storage and database access, and are enforced on the Firebase servers. So no matter if it's your code, or somebody else's code that uses you configuration data, it can only do what the security rules allow it to do.
For another explanation of what Firebase uses these values for, and for which of them you can set quotas, see the Firebase documentation on using and managing API keys.
If you'd like to reduce the risk of committing this configuration data to version control, consider using the SDK auto-configuration of Firebase Hosting. While the keys will still end up in the browser in the same format, they won't be hard-coded into your code anymore with that.
Update (May 2021): Thanks to the new feature called Firebase App Check, it is now actually possible to limit access to the backend services in your Firebase project to only those coming from iOS, Android and Web apps that are registered in that specific project.
You'll typically want to combine this with the user authentication based security described above, so that you have another shield against abusive users that do use your app.
By combining App Check with security rules you have both broad protection against abuse, and fine gained control over what data each user can access, while still allowing direct access to the database from your client-side application code.
Building on the answers of prufrofro and Frank van Puffelen here, I put together this setup that doesn't prevent scraping, but can make it slightly harder to use your API key.
Warning: To get your data, even with this method, one can for example simply open the JS console in Chrome and type:
firebase.database().ref("/get/all/the/data").once("value", function (data) {
console.log(data.val());
});
Only the database security rules can protect your data.
Nevertheless, I restricted my production API key use to my domain name like this:
https://console.developers.google.com/apis
Select your Firebase project
Credentials
Under API keys, pick your Browser key. It should look like this: "Browser key (auto created by Google Service)"
In "Accept requests from these
HTTP referrers (web sites)", add the URL of your app (exemple: projectname.firebaseapp.com/* )
Now the app will only work on this specific domain name. So I created another API Key that will be private for localhost developement.
Click Create credentials > API Key
By default, as mentioned by Emmanuel Campos, Firebase only whitelists localhost and your Firebase hosting domain.
In order to make sure I don't publish the wrong API key by mistake, I use one of the following methods to automatically use the more restricted one in production.
Setup for Create-React-App
In /env.development:
REACT_APP_API_KEY=###dev-key###
In /env.production:
REACT_APP_API_KEY=###public-key###
In /src/index.js
const firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,
// ...
};
I am not convinced to expose security/config keys to client. I would not call it secure, not because some one can steal all private information from first day, because someone can make excessive request, and drain your quota and make you owe to Google a lot of money.
You need to think about many concepts from restricting people not to access where they are not supposed to be, DOS attacks etc.
I would more prefer the client first will hit to your web server, there you put what ever first hand firewall, captcha , cloudflare, custom security in between the client and server, or between server and firebase and you are good to go. At least you can first stop suspect activity before it reaches to firebase. You will have much more flexibility.
I only see one good usage scenario for using client based config for internal usages. For example, you have internal domain, and you are pretty sure outsiders cannot access there, so you can setup environment like browser -> firebase type.
The API key exposure creates a vulnerability when user/password sign up is enabled. There is an open API endpoint that takes the API key and allows anyone to create a new user account. They then can use this new account to log in to your Firebase Auth protected app or use the SDK to auth with user/pass and run queries.
I've reported this to Google but they say it's working as intended.
If you can't disable user/password accounts you should do the following:
Create a cloud function to auto disable new users onCreate and create a new DB entry to manage their access.
Ex: MyUsers/{userId}/Access: 0
exports.addUser = functions.auth.user().onCreate(onAddUser);
exports.deleteUser = functions.auth.user().onDelete(onDeleteUser);
Update your rules to only allow reads for users with access > 1.
On the off chance the listener function doesn't disable the account fast enough then the read rules will prevent them from reading any data.
I believe once database rules are written accurately, it will be enough to protect your data. Moreover, there are guidelines that one can follow to structure your database accordingly. For example, making a UID node under users, and putting all under information under it. After that, you will need to implement a simple database rule as below
"rules": {
"users": {
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid"
}
}
}
}
No other user will be able to read other users' data, moreover, domain policy will restrict requests coming from other domains.
One can read more about it on
Firebase Security rules
While the original question was answered (that the api key can be exposed - the protection of the data must be set from the DB rulles), I was also looking for a solution to restrict the access to specific parts of the DB.
So after reading this and some personal research about the possibilities, I came up with a slightly different approach to restrict data usage for unauthorised users:
I save my users in my DB too, under the same uid (and save the profile data in there). So i just set the db rules like this:
".read": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()",
".write": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()"
This way only a previous saved user can add new users in the DB so there is no way anyone without an account can do operations on DB.
Also adding new users is posible only if the user has a special role and edit only by admin or by that user itself (something like this):
"userdata": {
"$userId": {
".write": "$userId === auth.uid || root.child('/userdata/'+auth.uid+'/userRole').val() === 'superadmin'",
...
EXPOSURE OF API KEYS ISN'T A SECURITY RISK BUT ANYONE CAN PUT YOUR CREDENTIALS ON THEIR SITE.
Open api keys leads to attacks that can use a lot resources at firebase that will definitely cost your hard money.
You can always restrict you firebase project keys to domains / IP's.
https://console.cloud.google.com/apis/credentials/key
select your project Id and key and restrict it to Your Android/iOs/web App.
It is oky to include them, and special care is required only for Firebase ML or when using Firebase Authentication
API keys for Firebase are different from typical API keys:
Unlike how API keys are typically used, API keys for Firebase services are not used to control access to backend resources; that can only be done with Firebase Security Rules. Usually, you need to fastidiously guard API keys (for example, by using a vault service or setting the keys as environment variables); however, API keys for Firebase services are ok to include in code or checked-in config files.
Although API keys for Firebase services are safe to include in code, there are a few specific cases when you should enforce limits for your API key; for example, if you're using Firebase ML or using Firebase Authentication with the email/password sign-in method. Learn more about these cases later on this page.
For more informations, check the offical docs
I am making a blog website on github pages. I got an idea to embbed comments in the end of every blog page. I understand how firebase get and gives you data.
I have tested many times with project and even using console. I am totally disagree the saying vlit is vulnerable.
Believe me there is no issue of showing your api key publically if you have followed privacy steps recommend by firebase.
Go to https://console.developers.google.com/apis
and perfrom a security steup.
You should not expose this info. in public, specially api keys.
It may lead to a privacy leak.
Before making the website public you should hide it. You can do it in 2 or more ways
Complex coding/hiding
Simply put firebase SDK codes at bottom of your website or app thus firebase automatically does all works. you don't need to put API keys anywhere

Restricting user authentication with Firebase

I'm using Firebase to authenticate the users on my application but, since the app is very early stage, I would like to restrict the login (or registration) to only users that have a specific code.
It looks like there's no option like this and I was wondering if there's any solution that doesn't involve a back-end.
Right now I'm using a specific code in the database that the user has to enter while logging in. If that code is not correct you can't login. The problem is the function (obviously) is executed on the front-end so a person with the right knowledge could easily modify the code and still access without token.
Is there a more robust solution?
if you truly want no back end, you can see my answer at the bottom here How to protect firebase Cloud Function HTTP endpoint to allow only Firebase authenticated users? , which involves taking advantage of the fact that every firebase project is also a Google cloud platform project and GCP allows for private functions.
however, there is an easier way: just wrap your cloud function logic with an if clause that checks for any of a number of things before actually executing the function
assuming, for instance, you're on the web platform, when someone invokes an HTTPS callable function from the front, it will be sent with data and context objects.
you could check for context.auth.email to restrict to specific users. or you could check for data.mySecretKey and since the check is occurring in your cloud function, no one could inspect your code to find the key.

Adding “Sign In with Apple” in Expo react native app that uses Firebase auth

I have a react native app that uses Expo (managed, not detached) and that uses Firebase auth to provide Facebook login and email/password login.
I now need to implement “Sign in with Apple” as per Apple’s new rules.
Expo provides a way to do this, and it works, returning the user’s info. But because all users are managed through Firebase auth, I need to take what Apple sends me and pass it to Firebase auth.
The Firebase docs explain how to do this using signInWithCustomToken. But that requires that I create the token. In Node this would be simple, but this app is serverless and I haven’t found a tool that can generate an RS256 token on the client. From the Firebase docs it seems that RS256 is a requirement. I’ve tried using expo-jwt with HS256 and Firebase returns an error that the token is badly formed. But besides using HS256 instead of RS256 I see no other possible problems. The token is encoded and decoded successfully as follows.
const appleJwt = JWT.encode(
{
familyName: 'M',
givenName: 'Greg',
email: 'apple_user#example.com',
alg: 'HS256',
iss:
'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit',
sub: serviceAccountEmail,
aud: serviceAccountEmail,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 3600,
uid: appleUid
},
key,
{
algorithm: 'HS256'
}
);
console.log('TCL: loginWithApple -> appleJwt', appleJwt);
const appleJwtDecoded = JWT.decode(appleJwt, key);
console.log('TCL: loginWithApple -> appleJwtDecoded', appleJwtDecoded);
It’s only when I try to use it with Firebase auth that it returns an error that the token is badly formatted.
return Firebase.auth().signInWithCustomToken(appleJwt).then(...
Note that the key and the serviceAccountEmail were retrieved from the firebase console.
I’m wondering if perhaps there’s some simpler solution that I’m overlooking. The community is awaiting word from Firebase on if they’ll provide out of the box login with Apple, like they do for other providers, so maybe I just need to be patient. But I’d prefer to find a solution.
A big thanks in advance for any advice.
Update 2019-10-15
I built a simple node server with an API that my app could use to generate the token with RS256, but Firebase still responds that the token is badly formatted when I pass it to signInWithCustomToken. Can’t see what’s wrong with it.
So, since I had the node server built, I just configured the Firebase Admin SDK and used the provided createCustomToken to generate the token. Firebase accepts it now when I pass it to signInWithCustomToken, which was my problem, so this issue is settled for me. After the custom Firebase sign in succeeds the first time, I write all the user data to Firestore. For subsequent sign ins, it just updates the last login date in Firestore. Hopefully Firebase will still provide their own solution soon too, since having a separate node server just for this is not ideal.
Firebase Auth now supports Apple sign in across all 3 platforms:
https://firebase.google.com/docs/auth/ios/apple
https://firebase.google.com/docs/auth/android/apple
https://firebase.google.com/docs/auth/web/apple
The Firebase team is working on implementing this in the official sdk
https://github.com/firebase/firebase-ios-sdk/issues/3145#issuecomment-510178359

BigQuery and GCM

I'm trying to create an Android app that extracts information from a table in BigQuery. In order to do this, do I have to have to implement Google Cloud Messaging? If so, do I have to have a GCM server? Is there a way, the app can authenticate directly with BigQuery and fire a query?
If you just want to make calls to BigQuery, you shouldn't need anything like Google Cloud Messaging (I'm not actually sure what that is).
You can either use the BigQuery java client (info here) or you can make raw http requests to BigQuery (you'll need to use Oauth2 for authorization).
You also might consider using an appengine app to proxy the requests to bigquery. That can make auth easier, so you don't need your BigQuery credentials in the android app.
I was trying to do the same.
I am able to do it in the Xamarin Studio(which uses C# API library of Google APIs).
Well..
First of all you need to authenticate the user..
The authentication is done using
private readonly static Google.Apis.Authentication.OAuth2.GoogleAuthenticator Auth = new Google.Apis.Authentication.OAuth2.GoogleAuthenticator (clientId,new Uri ("https://www.example.com/oauth2callback"), Google.Apis.Bigquery.v2.BigqueryService.Scopes.Bigquery.GetStringValue ());
Intent authIntent = Auth.GetUI (v.Context);
StartActivityForResult (authIntent, 1);//This will open and ask for Google account
So Auth is the Authorisation object.
var Service = new Google.Apis.Bigquery.v2.BigqueryService (Auth); //Creates the BigQuery Service
string query = "SELECT year, SUM(record_weight) as births FROM publicdata:samples.natality GROUP BY year";
Google.Apis.Bigquery.v2.JobsResource j = Service.Jobs;
Google.Apis.Bigquery.v2.Data.QueryRequest qr = new Google.Apis.Bigquery.v2.Data.QueryRequest ();
qr.Query = query;
Google.Apis.Bigquery.v2.Data.QueryResponse response = j.Query (qr, projectId).Fetch ();
Google.Apis.Bigquery.v2.Data.TableRow row = response.Rows.FirstOrDefault ();
Google.Apis.Bigquery.v2.Data.TableCell cell = row.F.FirstOrDefault ();
The above code is with respect Google APIs .NET library.
I am trying to use the Java API library.
I'll update my answer as soon as I am successful.
Hope the above answer gives you a starting point or an idea till then. :)