Protecting Node JS REST API using Firebase Tokens.

I once came across a challenge where by I wanted to use Firebase Auth, and I have Node JS app. So the web dashboard with Node JS with Express, the REST API for mobile app was also made by Node JS and Express.

The issue arise as how am i going to protect my routes using Firebase Tokens. I signed up users using Gmail, Facebook or Email and Password (Firebase) on the mobile app.

When you use Firebase Auth, as soon as the user signed in, you can get tokens which are unique and contains details of that specific user.

Before that i used to have JSON web tokens then decided to switch to Firebase Auth

I have looked for solutions on Stackoverflow but i didn’t find any. So here how i did it. Please feel to add your comments.

1st — As soon as user sign into the mobile app — any if android or IOS, Firebase User instance becomes available and you can use this to get the token in any — activity or fragment.

FirebaseUser user = mAuth.getCurrentUser();user.getIdToken(true).addOnCompleteListener(task -> {

if (!task.isSuccessful()) {
Log.w(TAG, "The getInstanceId failed", task.getException());
return;
}

if (task.isSuccessful()) {

String idToken = task.getResult().getToken();
final String userId = mAuth.getUid();

Log.d(TAG, "The token is : " + idToken);
//save the token on shared preferences - u need to get a refreshed token whenever you call your end point using volley, retrofit or any other networking library-so save this prefManager.setGlobalAccessToken(idToken);

}
}).addOnFailureListener(e -> e.printStackTrace());

2nd — After you get the token and store it on shared preference, now you can send the request using volley or retrofit and put token on a header. Request method can be any — GET, POST, PUT etc, we only concerned with header.

StringRequest myRequest = new StringRequest(Request.Method.GET, "END_POINT_URL_HERE",
response -> {


try {

JSONObject jsonObject = new JSONObject(response);
Boolean success = jsonObject.getBoolean("success");

if (success) {
// - you data received here, you can broadcast, and any activity or fragment listens, they will catch it :)
}

} catch (JSONException e) {
Log.d(TAG, "The error here is " + e.getLocalizedMessage());

}
}, error -> {
error.printStackTrace();
Log.d(TAG, "The error in getting user profile is : " + error.getLocalizedMessage());
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("firebaseUserId", firebaseUserId);
params.put("category", "free");
return params;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Authorization", token); --put your token here.
return params;
}
};

AppController.getInstance().addToRequestQueue(myRequest);

3rd — Lets switch and see how you can protect your REST API routes. Create a function and on all your routes, use the function as your middleware. You need to use Firebase Admin SDK for this to work, —

Middleware function for protecting the routes

Then on your routes do this.

Give it a try! :), and share your comments.

A movie junky and a software developer. #python #java #swift #NodeJS #mongoDB #API

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store