Server-side Firebase Authentication Using Express JS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
how to implement server side authentication using firebase and Express GS let's build a simple app here is what we are building today it is a multi-page application we have our home screen where we can click profile link and profile is protected route so you cannot access it without being logged in I already have prepared the user test Ofcom let's log in and we get redirected to profile page if we log out we will get redirected back to signing screen there is also sign up a sign-up screen but we don't really need it I've edited there only so that you can create new users I've created an example repo that I will link in the description and this repo contains two folders two steps first step is to create the structure of our application create the HTML views I'm not going to use any front-end framework not react or view or anything it will be just plain vanilla JavaScript and HTML and also set up the server it won't really contain any code for now that will manage the authentication part but we will at least set up the routes that we will need to process and in the step number two we will actually implement the firebase part where we will authenticate our user and preserve the state on our back-end now let's go through the code and see what you have to do here let's begin with step one what do we have here it's a regular Express application will be using Express as our server we will need a body parser plugin to be able to parse the post request body as JSON we will use C surf package to tree to protect us from CSRF attacks I've added a link I've added a bunch of links about cross-site forgery so first it's Wikipedia page and then it's all WSP website cheat sheet about cross-site forgery and how to prevent it I recommend you reading it and here is a link to the package we are using here si surf that will basically create a token that we will send from the page that will be making our login request so that we know that this page was created by us this token will basically verify that this is our side our form it's legit and we can actually log in through this particular form read about it on Wikipedia it's it's gonna be useful it doesn't have anything to do with firebase yet so we install that package we also install cookie parser because we will have to work with cookies we'll have to write the cookie and we'll have to read the value from it and then we have the code that initializes our application so first we create the CSRF middleware it will basically check if we have the required cookies in each of our requests then we define the constant for our port we either take one from environment or use the default 3000 and then we instantiate express we set the engine to HTML it doesn't really matter what you use in my case I didn't want to bother with bug or Jade or whatever so I decided to just use plain HTML and also a set up the static folder which I need because I wanted to use and with P CSS this is a little CSS file that provides decent default look for all your HTML elements so you basically can own it all the classes use just regular HTML elements National tags without classes and they will already look nice so it's quite useful then we enable the body parser this is so that when we take the body property of the post request that we got from our front-end application we don't have to bother parsing it as JSON manually so it already comes parsed as JSON so we can use it as an object then we use cookie parser so it automatically works with cookies and then we use the CSRF middleware that sets and automatically checks the CSRF related cookies next what we do here is I create another middleware if you don't know how Express GS works is basically a stack of middlewares each middleware has some logic in it and after the logic is executed it calls the next middleware in the stack so we basically have a pipeline that works with our response and request objects so when you have a request first thing that will happen is all those middlewares that we define here so the static middleware at an request goes down the stack and we parse it with bode parser and each of those middlewares can do something with request object somehow modified then we use cookie parsers just ref middleware then there is my middleware that takes any requests and sets a cookie called access ref token with the CSRF token from request and then I called function next that passes us down to the next middleware next middleware is login or signup or profile or whatever because they are a little bit more picky they unlike the first one that will be triggered by any requests those will be triggered only by specific routes so for example if we open the route route slash we will just render our index dot HTML if it's profile then it's all signup it should be profile actually if it sign up it sign up and if it's login its log in dot html' so basically we add routing here and then in the bottom of this file we just launched our server by calling listen and then passing it port and a callback so that we just know when the server was launched successfully now as you can see on each route we're under some HTML file those files are located in the views folder and if we open for example index dot HTML contains just the basic layout to show the title home page header the information that this page is public and the link to profile if open profile page we also have the header and we have an information that this page is private and then we have a link to log out because if we can open this page then it means that we are logged in and then we might want to pull this log out handle to just remove the session cookie and session cookie is the way how we will preserve the logged in state we will create a long living cookie that will live several days I think five days and this cookie will be HTTP only which means that only back-end can access it and fronton can either modify or read it so it's only back-end that will be able to touch this cookie next we have two pages that will actually use firebase in them its login and signup page they're quite similar the only thing that will be different in them is that signup will actually create new users we will pull this handle and log in will just log us in and those pages they have to pull a bunch of JavaScript files so what is going on here is that we have a bunch of scripts on login page we we currently have them in the bottom of our layout and what happens here is first we load the firebase SDK then we load firebase off SDK because we will need authentication methods for firebase then we have the cookie library that allows us to read cookies and we'll need it because we need to read the CSRF ok and here I have the listener that is listening for Dom content loaded event and this is because I wanted to write differ for each script and actually put them in the header so that we are not blocking the rendering and we load all those JavaScript assets in a non-blocking way and because we need to know when it will load them actually we will add this listener Dom content loaded that will be triggered when everything don't related will get loaded on our page and then I try to get element by ID login and it's the form and I had on submit listener that just prevents the default behavior so for now we're we're not having with so for now we don't have any logic there we just prevent the default behavior which is just get by default the action of this form okay that's the first part we have the structure of our application to start working with firebase first we will need to instantiate the firebase application and enable admin SDK let's do it now go to console firebase google.com press add project you will have to pick the project name and let's say it's Express server off continue we don't really need the analytics so press create project we wait edit well and we are finally done now we need to do two things we need to go to authentication and enable email and password sign-in method so we enable it save this will allow us to log in with email and password if you need you can enable any other way of signing in then we go to this things on the general tab you select the web icon I don't know vegetable tag one you click it you name your app somehow Express server both register app and it will give you the settings that you will need to use in your front-end now I'm not going to copy them because in my application I've already created the one before because you saw you saw it it works so this one is only an example how to obtain them but you copy those settings and then you will need to go to log in HTML and paste it here it will look like this when the page is loaded first thing you do you paste the thing that you got from firebase where you basically instantiate the app and then you call firebase both set persistence none this will basically turn off the persisting of the loading state on the firebase behalf because we will not need it because we will create our own persistence layer that will be using the session cookie as I told you before and then here is the submit listener that you saw previously okay we've set up the front-end part by pasting the configuration of for the firebase to our login template in Dom content loaded callback now we need to set up the backend side go back to firebase close this thing go to Settings service accounts and here you need to click generate new private key this thing will create a JSON file that you need to download here we go it says that I need to download it I'm not going to do it now but you will have to do it what you do next is you copy the contents of this file and then you save it in the file called his account he dot JSON so it will look somewhat like this with of course your numbers and hashes and whatnot that should be it you should be now all set up on the firebase behalf now let's get back to our code and see what do you still have to do in order to have server-side firebase authentication so first thing you see here is that we have another package called firebase admin don't forget to install it all those packages that I'm using here on server part server side I have them installed through NPM and its bori parser cookie parser C surf AGGS Express and firebase admin don't forget to install them if you will pull this example from github it will be enough to just run NPM I or better yarn to install all the dependencies in this project now we go back to server DoDEA's and we instantiate our admin site our server-side firebase we get an instance of admin from firebase admin we load the service account key JSON file and then we call initialize app passing our service account JSON as a credential certificate and then it will handle the authentication and the initialization part automatically and we also have to set the database URL you see this database URL here basically what it editor is this little snippet that is on service accounts page so I copied it and basically pasted it in the beginning of server instantiation that is it for now everything else remains the same let's go to login dot HTML file so what happens here after we got our firebase initialized after we've initialized our firebase library and recess and we set our persistence to none so that firebase does not persist it in local storage or anything we start listening to the submit event of our form our form has two fields a login and password so first thing we do we get those values from the event and then we call firebase off sign in with email and password we pass in their login and password and it returns a promise promises allow us to work with deferred data the values that will get later so here it will make a network request and then we can add the van call back we will get a user object and we'll be able to get the ID token and when we get this ID token then we call fetch which is built in browser API to make a post request to session login of our expressjs back-end we're going to send a bunch of headers telling that we're working with JSON here and our CSRF token that we get from the cookies this is the value that we actually wrote to the cookies using this particular middleware so I'm using CSRF token generated by C surf library I put it into the X CSRF token cookie and then in log in HTML when I'm doing the Ajax request I'm getting this value from the cookie and sending it in the header to prove that it's me Maxim that got this form like I'm not a hacker or someone I am just using this form legitimately and then I pass the body containing stringify version of JSON we basically take the object containing one field ID token that we got from firebase our identification token and I pass it in string to fight Jason after the request was performed I call firebase of sign out I sign out from firebase because it's not needed any more it will be the back end that will handle all the firebase related activities and then I navigate to profile because now after we logged out after we logged in on our server we should be able to access this so navigate to profile now what happens when you fetch this session login handle with through the with a post method let's open our server the GS and scroll down to this method declaration here we have a post handler session login route that takes the ID token that we sent to it as a body of our post request as you remember we've installed JSON parsing middleware so we can just take the body and take the ID token from it as a field because it's already an object and we cast it to string and then we calculate the expires in value what we do here we need to have a value in milliseconds so we multiply everything by 1000 so that we do the calculations in milliseconds then we multiply 60 seconds which is a minute by 60 which is an hour by 24 which is a day now and then by 5 and it's 5 days so expires in five days and then we call the add minute by which we initialized here by requiring it from firebase admin we call authenticate we ask it to create a session cookie using the ID token and tell it how long this cookie should live 5 days and after it's done then we get this session cookie from the callback we set the session cookie with options and the most important options here is HTTP only we want this session cookie to only be available from the backend so only back-end can access read and modify it so that front-end won't be able even to know that there is such cookie javascript won't see that there is cookie called session you will though see it in your developer tools in chrome at least maybe not in other browsers and then we send the JSON with status success so application knows that everything is fine if at any point we get an error we will send for one unauthorized actually there is another case when you will send unauthorized is when CSRF middleware will see that whoa the CSRF token is not matching it's someone else trying to mess with our forms maybe trying to send it from some other place not our website cool at this point on the front and side you already get got authenticated you got redirected to that profile page and if we go back to server Jess and see how profile looks like it's protected route so what we do here we try to get session cookie from request cookies and that this field is added there by cookie middleware that we initialized before we get the session cookie from it or an empty string if session cookie is absent then we call admin off verify session cookie so we call verify session cookie from the auth module and we send the session cookie and make it check if it was revoked already passing the second argument true then if everything is fine we render the profile dot HTML and if we have an error then probably something is wrong with our cookie and we need to redirect the person to login page to repeat all the process again now if open profile dot HTML you will see that we have layout header paragraph saying that this page is private and we have session logout link and this is the last thing we're gonna look at today so we have session login we scroll down and we have session logout this is regular get request handler that clears the session cookie and redirects you back to login and as you don't have session cookie anymore if you try to go to profile it will try to read this cookie from the request it will fail because we removed it and then it will redirect you to login because session cookie will be an empty string and of course it's invalid thank you for watching if you have any questions about this implementation then you can ask me in the comments I will leave a link to the repo that will have this code that you can play around and try to use your settings of your various application and if you have any problem then I would prefer that you send me an example repo where it does not work so I don't have to guess what exactly went wrong so good luck and I hope this video was helpful to you
Info
Channel: Maksim Ivanov
Views: 60,014
Rating: undefined out of 5
Keywords: firebase, express js, node js, server authentication, firebase server side code, firebase server authentication, javascript tutorial, firebase tutorial, expressjs middleware, express js tutorial, firebase developers, firebase authentication, server-side javascript, session cookies javascript, session cookies, firebase session cookies
Id: kX8by4eCyG4
Channel Id: undefined
Length: 22min 2sec (1322 seconds)
Published: Mon Apr 20 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.