Firebase admin sdk | Express Node.js | Reusing the token

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone welcome back to my channel and this amazing video i am aditya in this video we are gonna see another interesting concept so we will see how to use firebase jwt token or how to reuse the firebase token for your own server side backend and how you can use the already authenticated firebase user to serve from your own server side and so without any further ado let's begin so okay let's understand the scenario like what we are going to do today exactly and where this scenario will be useful so suppose you have a mobile app or a front-end app maybe just a single page application or a server side to an application whatever it is like a web application or a mobile application whatever now you started the application development and then you wanted to keep it minimalistic so you started to have like firebase functionalities in it maybe the authentication data storage cloud storage and all those stuffs later down the line you decided that you need your own backend services in place and you want to integrate your current app with your backend so you decided to have a back end let's say in express or laravel doesn't matter but you want to now have your own backend plus the firebase functionalities in place plus your front end now you have two options to securely connect your packet with the front end the first option is to have your own jwd configuration in place so if i take example of laravel and that you can use passport or if you want the access token configuration you can use phantom if i take example of express or fast api then you need jwt token for express there is jwt web token or express jwt for fast api it has its own jwd package so you need to use those and make sure you create a token and then the token is valid for certain time and so on and so on so these things have nothing but you are doing the same thing again and again because for firebase you already get to get a token and you have your own token system in place as well so it's kind of like doing double work so what's the best solution in this case so the second option for you might be or potentially be the best solution so in this case you just reuse whatever firebase token you have because the user who is making a request is already authenticated with your firebase service and then whatever token they use you send it from the front and you use firebase admin sdk to make sure that the token is valid and once the token is valid you serve the user normally with whatever data or response you want to serve so for this before we dive in in detail let's first understand what is this admin sdk so as i said and just in brief like it is just extending the functionalities of firebase features like the authentication data base cloud storage and all other things they are just extended for the backend or you could say you can use firebase functionalities for the backend ideally these firebase services are made for mobile applications or to the minimalistic case for web front end where you don't need to write your own backend so you could say this is more like a serverless architecture or a function as a service architecture so you get everything in place so now when you integrate it with your backend so there are five official languages supported in this so there is node.js which supports all the features of firebase for backend java then with some features python with one feature less than java go one feature less than python and c sharp one feature less than go so it's kind of like in that sequence there is an unofficial package for php but it doesn't supports all the features however it suppose supports most of the features so that's all being said now in this video we will be using express framework so it's a node.js framework we will create a scenario where we will have a view application in front end who is already using or which is already using the firebase login system then our express app will use the token received from the view app and authenticate it sorry validate the user not authenticate but validate the user and then serve the user so to save some time i already installed the view application sorry this is express so this is view application already in place so i have already so this is just the like this thing i have added it i will explain you what these things are doing uh i'm using view 3.2.6 so that i could also use the setup api sorry not set up api but the setup script so if you haven't seen the video for view 3.2 setup script please do check the video i'll put the link in the description uh i already have a firebase front-end module which is nine point something version already installed for over here and then on the express side so it's just like here we will create our api routes in a moment and i just have like a very simple express application so if you haven't seen or if you're new to this express i would highly recommend just have a look on the documentation because uh the code this piece of code will be already there but what it is exactly doing here is we are creating instance of express provided we have already installed the express package once we create the instance we sorry we are importing it over here and we are creating the instance over here the app is the instance we are setting the port number of 3000 that we are saying that these are our routes so app.get means the get request on the root route so forward slash route is for slash is the root route we are having a request response callback and we are just sending a response of hello world which i'll show you in a moment or i can show it now on the browser which shows something like this and before that we are listening to the server at port number 3000 and we are just consoling it that we are listening at this port so that's all on in from fire sorry on express side so i have also installed the firebase admin sdk with node 1 so node 1 is just an optional step just for you don't have to close the server and restart it again so you just save the things and like refresh the browser and it works for you uh here is the firebase admin sdk so this is for the node.js sdk and this we will be using for today's application so to make it more kind of authentic api service we will be using course as well so this is the node package for making sure that the requests are coming from the right url sources because in this case we are authenticating our uh front-end application but in in suppose if we want to just authenticate the uh mobile application then in that case scores might form an issue then in that case you just need a token authentication in place so you just need to make a note over here like a small note that what are you gonna serve your api mostly for is it the front-end web application or it's just the mobile application or is the both if it's the both then just keep it token you can skip the course in that case so that all being said so we will now jump into the coding so first we will start with the express so we'll start with the express site so let's go to the express side so now this both are javascript applications remember the one is node.js the other is playing javascript so front and javascript so it might be confusing for you guys which can understand so whenever i will switch from express to view view to express i'll let you know so now we are in express so here uh in i have just added a new file api.js so that we can keep our api route separate so nothing different we will just call here a router which will come from uh express dot router and along with this we will need uh okay let's do this actually we need an expression as well json all those stuff so i'm going to take another app here let's take api so that it's not confusing so require express and then here i can just say bi dot router because we are already having it over here then once we have the router in place we can get the course uh i have already installed the package if i am correct yes i already installed it of course equal to require course okay now first thing first is we need to set up the course so we will take a variable in that we will take our course option okay now these calls option will be an object now this is an optional step again so you can have a white list of urls that you want to allow for this specific api route to have access to so i'm going to create a white list and in this white list i'm gonna give the view app that is running on 127.0.080 and then here i'm gonna do a bit differently so if i go to the documentation over here of the course npm documentation if you if i go down over here so this is like the basic way to set up course but uh if you want to do it with a more precise of that uh white list and everything you have already a ready-made piece of code over here so what we can do is we can just simply copy it but we need to make a small change if required so here one thing we need to make sure is that this once you place this course option [Music] this thing will not allow your own url which is the h localhost 3000 to have access to this because it is not in the white list so this api route is strictly made to be accessed by the urls that we have authenticated to which is not the origin itself like the origin when i say in this case is this origin or you could say the host yeah the host in this case so you just need to make sure that you are keeping this api route separate that's why i kept it separate so that this is only accessible for and only by the web applications that we have white listed okay so what is this course options doing here so we have path we are having an origin with key value parent object and this origin is nothing but a callback so this callback is doing nothing different it is taking the origin so in this case origin will be the request source so in this case if i'm making request from this origin so this is the origin over here and the second parameter is the callback again so this callback is different we'll see that here it is doing that just a simple array check so in the white list if it sees the origin then it just says that everything is good go forward if it doesn't seize the origin in the white list it will throw an error saying that not allowed by course like it's very simple so that being said we just need to make sure that this course options are applicable for all the route so here i'm gonna say uh [Music] course sorry router dot u cars car options now you can see that this thing is a bit weird here so of here it's showing okay that's great i think it's everything is good so right uh okay great so far so it's okay so now here we just need to give the that body parsing so here i just need to say our router dot use api dot json api dot json is coming from this express so now we are [Music] we just need to set the get url so here i'm going to say router dot get and this time to get would be just the root url and here i'm gonna give request response function oops and here i'm just gonna say like api request response simple and then over here i'm just gonna export this i'm gonna say module dot export uh router so once that's done we can get the get the exported module over here so i'm gonna take it over here i'm gonna click on router let's take it api actually so that we know that this is an api route and we will get the api and here we will say app.use and then we will pass the url so this will be forward slash api whatever url or request has a prefix of api will go to our this route over here okay now let's test this quickly so what i'm gonna do is in my view app uh just gonna uncomment the code i already have in place so here uh let me explain what i'm doing here so this is the setup script in place so hello world component just export actually we don't need this because we are not using it so i can just remove it uh then we have uh these two functionalities from firebase but before that the app is initiated over here so these are the credentials of my firebase app please do not copy this because i'm going to delete this app once the video is finished so these are the functionalities of my firebase sorry credentials of my firebase apps i'm initializing the app over here once that's done then i'm just importing the get on and sign in with email and password functionalities from firebase auth package so once you install the firebase package you get all these things in place if you want to know in more details like how the sign in email and password register with email and password works so have a react native with firebase video with that so that might be of some help for you guys so please do check down check out that as well the javascript is same it's just different than like the html or the handling the part of input and output changes but the javascript of five system is the same so we have this sign in with email and password so this is the user i already have in place so we're just using the get dot functionality here so let's break it bit down and then uh we are just passing the op variable here and then the email and password so the auth instance goes over here that the email and password and then the whatever response we get would be the user credentials so you're just getting the user and we will just put the user over here so that we know that is the user so let's say control dot log user user okay now this step is something only this piece actually we are already consulting the user we can do it from here so this step so if i take it down sorry over here so for this step over here is checking and getting the token and passing through server so this piece of code you will get it in the documentation again so if i go to uh this one on this one as well this one so verify id tokens so you just need to use the web approach because we are using the web approach if you are using react native then you just have to follow the same approach just for firebase 8 module for react native but for other web approach like a pro plane reactor view app you just you have to use firebase 9 module because for react native i guess firebase 9 is only supported with core react native just let me know in the comment section if i'm wrong in this case but for expo definitely it's just firebase 8 till today's date uh for mobile applications there are various ways to get it open and pass it to the backend but for the web one we will just follow this approach so here we have that auth not this one this one so we have the auth current user then we are getting the id token now this get id token function is a promise or it returns a promise so we are just resolving that promise over here so whatever token we get we will be displaying it here plus after we get the token we will be passing it with an axios request so just uncomment the axios code so axios we will we are just going to get the url where the my server is residing forward slash api and as this is just forward slash api so it's going to the root route and here we will pass the headers in a moment but for now i'll keep it blank to show you the token authentication process as well and then whatever response we get we are just consoling it if i save this go back over here and refresh the page see it in the console so we are getting two errors so one error is about the course so let's see what's the course issue we are getting so we have a localhost 3000 api version okay let me see if i put the correct origin so 8080 yes uh http 127.000.1880. [Music] okay yes it is so let me see what's showing in consoles it says not allowed by course uh local those three thousand okay all right so it is just getting over here if i go in my browser refresh this page okay this is great so let's see why we are not allowed by course so okay for now if i just comment this line and refresh the page okay so it says network error [Music] all right so it's just the course issue so let's fix that course issue let's see what we are getting it has been blocked by no access control allow origin enter okay so okay we can uncomment this and here is these uh course options we're using the course with this course options that's okay okay what we are doing wrong here let me see oh yes so one big problem was with just a colon over here one small problem and yeah so now it should work if i go back over here refresh the page and there it is so we are getting the request response correctly that's great so our cars are in place now we just need to send a token and before that to send the token and have it work properly we need a service account to use firebase admin sdk so if i go over here in the instruction for node.js we did the steps of actually we haven't properly did this step so we just installed it like i installed it before but we haven't just initialized the app and everything so if i go over here it is asking me to create a service accounts then it is asking me to create a new private key and then confirm by clicking the generate key and then securely store the json file containing the key okay so now what i have to do is in my project here so i already have given a service account if it's not there you just need to create a new service account and once you create a new service account then you will have an option to select the or just code snippet to select how you would like to proceed forward an integration of admin sdk so in this case i just need to go and create clear click here generate new private key it will say that your private keys give access to your projects firebase keep it confidential great i will then it will download it and that will go in my downloads so i'll just quickly get it from the downloads and paste it in our uh code over here so just give me a moment i'll just do it quickly all right so we have a json file over here and you'll see like this is the format you should get again please do not copy this because this is going to get deleted once the video is done so i'm going to delete the service account as well so you might stress an error if you just try to use this so this json file we just need to use it so i'll just rename this because the name if you see like it's something weird name so i'll just do it something like firebase cred dot json simple naming now the good thing about express is it's a micro framework so you don't have a project structure in place like other frameworks and you can you are having your own freedom to structure it but it's like a double edged sword it's kind of like a drawback of it as well because here you like as you could see like my project though it's small but the files are like all cluttered at one place so it's i will just keep it as it is for now not gonna structure it properly but if you want you can always structure it like keep these two files outside take this json file and keep it over here and controllers and everything can be in separate folders like however you like it so pros and cons of console express so let's go to firebase credits we have it already there so that's the json over here now we just need to go back and just see how it's doing so here it is saying that we just need to get the firebase admin then service account that would be the path over json file and we just initially initialize our app so let's do that quickly so i'm gonna go over here now what i want is on every or particular route i want a token authentication there so here i'm going to create a middleware callback you could say i'm going to say const auth token verify middleware now this middleware is gonna take it's gonna be a function which will take request response and next now first thing first we just need to get this piece of course i'll just copy this piece of code from here and paste it over here okay so here is stop back to whatnotwhatnot.json we will just say this will be part for firebase credits.json now this will initialize our app so that's great now once our app is initialized next we can go forward with the token check now what i'm going to do is in my headers over here i will be passing or where is it removed it will get it back over here so headers and then our headers will come here now inside these headers i'm gonna pass the token as an authorization better token okay so what i'm gonna do here is i'm gonna in our express so here i'm gonna check for request dot header so i'm gonna take font string i'm gonna do request dot headers and from that i want the authorization editor try the agent header now from this authorization header so whatever authorization header i'm going to get so it's going to be space separated string so better space token so i just need to split it so i'm gonna split this thing i'm gonna say split with space okay now if this is a blank string or if it's not there so this will throw an error or this will say something like it's not working or something will go wrong here so what i'm gonna do here is i'm gonna say if this is there then do this else keep this string as not okay this string is now so it's not token string for now i will just send the response no token or sorry no header provided okay then suppose if that string is not null if that string is great and going it's good to go forward then i will check the first position in that array because how this okay let's first console.log how this token thing is going to look if we have the token in place okay so let's go back over here in our app uh save this over here home dot view that's great so now here this is express in the console refresh this go back over here in the console over here it says api request response yes because we haven't put the token middleware so here we just put that up so on this route get this is the url of the route not the url the route this is our middleware as a second parameter and the callback or the function to process on that route so let's go back again refresh the page and here you will see no header provided which is okay why because we haven't provided the header now let's provide the header so i'm going to say authorization header this is going to be a better token let's use backtake so that we can use it open here and our token will be nothing but this token over here so i'm just gonna pass this token to the back end now if i go again refresh the page it will throw an error of api uh 500 internal server but let's see what's the error so if i go over here it says uh the default firebase app already exists this means you call initialize more than once without providing an app name as the second argument let me refresh this okay now this is refreshed and if i refresh this here okay so this is still here we are saying we are seeing something and now if i go to this here you will see that the space like the string was where a space token we split the string with space and we got first as a better and then the token this is the token we need to use to verify the user so what i'm going to do now is in our app over here i'm going to make sure that if the token string is blank else if now if you want you can merge these two in one is like you can just have your if not to constrain and and uh your uh token string first opera first index uh is not present something like that then no request no header provided just to keep the message separate i'm gonna do it in a two l if else if loop kind of thing so here i'm going to say if token string of 1 if it's not there that means press dot send no token provided and if everything is there in place l in that case what i'm gonna do is i'm gonna just verify the token and proceed forward with whatever i have so here uh so where is it over here so i already have this piece of code so i have to just do something like this here so here i have to take cons get up so i'm just restructuring it and this will come from firebase admin okay we can just grab this piece of code go over here paste it here simply and here so okay so verify token so this id token would be nothing but our token string parameter and if this token is correct that means we proceed forward over here if this token is not correct then we will handle the errors okay so what i'm gonna do here is i'm gonna say if this is correct so this is the uid so here let's console the uid as well console.log uid as well as we will just proceed forward with whatever we have so it will go forward in this area but if it's not there so in the error we will say rest. whatever the error is so we'll just throw back the error now if i go back again here refresh this refresh this so it is saying 500 error okay let's i guess it has to do with the initialize app again so okay let's try to fix this so here uh okay let's see what's this is saying okay no worries so a good fix for this i can think of is to [Music] let's do like this we'll take cons firebase app equal to null and we will do if not so we'll just put this outside over here and we will do if not firebase app then we just do firebase app equal to this and it should be good so if we go back so this is refreshed this we refresh and it says again an error so what's the error assignment to constant variable uh oh yes we just need to do it left not const so this should be left refresh and refresh this again and there it is api request response so we put the token the token was right and if i go to console now over here we are seeing the uid so let's check if this is the correct uid should be let's double check so if i go to my authentication and you could see 3bk bka something something 72 here it is uh 3 bk something something 72 okay so that's perfect so this is how you can authenticate or if we use the token now all we have to do is once this is done so if i go back again over here so this is going all the way to here perfectly so if i go to this console again to double check yes api request response that's perfect so this is how you could do it now in case if you want to make it like a proper 401 error so in that case simply what you need to do is uh where is that response. and if i remember correctly we'll see we'll get an error if you're doing something wrong so here as well and now all we have to do is mr token here now header provided refresh okay this wasn't restarted so let's start this actually it is send only i'm pretty much sure yes yeah there it is so bodies just refresh and there it is unauthorized so you can also have this 401 error to handle in your axios and then take it forward so that's all for this video hope you enjoyed this video if you like this video please hit the thumbs up button if you haven't subscribed to my channel yes yet please do subscribe to my channel and if you feel this video is worth sharing please do share with your network so let me know in the comment section uh what next you would like to see also how do you feel about this video so that's all from me till the next time goodbye
Info
Channel: WebDevWithArtisan
Views: 674
Rating: undefined out of 5
Keywords: vue, express, firebase admin sdk, nodejs
Id: _3xj8t_zax8
Channel Id: undefined
Length: 35min 21sec (2121 seconds)
Published: Fri Oct 22 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.