Build and Deploy Secure Serverless Functions with Netlify

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello friend automating things on a computer can be challenging if you've ever written any amount of code even a single line of code you are a real developer and don't let anyone else tell you otherwise in this tutorial you're going to learn how to build serverless functions with javascript deploy them to nitlify and secure them with octa let's get started serverless computing sometimes referred to as functions as a service is an on-demand approach to providing back-end application services and perhaps an api the serverless architecture is an excellent solution for many use cases where an application needs a back end occasionally or periodically or maybe a back end that can scale to meet a demand like a big spike in usage or traffic netlify that we're going to be using in this tutorial is a hosting company that dramatically simplifies deploying websites and serverless functions which they call netlify functions with continuous integration and other really awesome features octa is an identity and access management company that makes adding things like authentication and authorization to your applications very easily before we jump into the project there's a few things that you're going to want to have on your machine on your system and the first of those is nodejs i recommend version 12 or higher as of this recording version 12 is the latest stable and long term supported release of node.js you can go to nodejs.org and click on the download button for your operating system however if you are running on mac or linux i highly recommend that you go find mvm the node version manager and install that on your system first nvm is a really great command line utility that allows you to install versions of node including you can exp you can have version 12 installed on your system and version 14 if you want to experiment with some of the new features coming out in the next release of node and you can switch back and forth using nvm another thing you're going to want to have is a netlify account you can go to netlify.com and sign up for a free account there's a number of things that you can do with netlify that cost you nothing and the examples of this tutorial that we're going to be going through will not cost you anything another thing that you're going to want to have is a octa developer account this is also free and it's free forever you can use this for any of the proof of concepts or small applications or anything for up to a thousand monthly active users which is you know fantastic i use it all the time you're also going to want a good code editor and if you don't already have one i recommend visual studio code i use this all the time and i think it's one of the best javascript and node.js debugging tools and editors available all right so let's get into creating some code so we need to create our serverless project to get started you want to open up your command prompt or your terminal depending on which type of operating system you're on and change to the folder where you normally store your projects for me i install i work on projects in a folder called projects and in this example i've got a folder named tutorials so start by creating a directory if you're on windows you'll use the md command but i'm going to use make dur because i'm on mac and let's call this this secure serverless tutorial and then change to that directory to start any new node.js project which is we're using node as a as a starting point it's we're not building a node application we're building a front-end application that uses uh some node type things uh with the serverless functions but any type of project that uses node and node modules and the the ecosystem that's around node and npm we need to have node.js installed so one thing you can do is type in node-v at the command line to see if node is actually installed and working correctly on your system if you get an error with this command then that means that either you don't have node installed or maybe you just now installed it and you need to restart your terminal or your command prompt or or you know worst case scenario you might have to restart your computer hopefully we're beyond those days uh where we have to restart our computers every time we install something but um it's still it still happens sometimes all right so with node installed node comes with the npm the node package manager and we use mpm to initialize our project so npm init dash y dash wise uh argument tells npm to just whatever the defaults are create a a project file with those defaults so it creates a file called package.json in your folder and depending on your defaults is going to populate this package json with those the package json is a way for node to keep track of dependencies such as you want to install an external library to use in your project when you use npm to install that it's going to add a reference to that dependency into your package json file and speaking of dependencies that's what we need to do next so there's a number of things we need to install one of the things that i install first before i do anything else is install mp um install eslint eslint is a linting tool for javascript it helps us to identify mistakes in our code uh common mistakes um maybe unused variables there's there's lots and lots of rules that can be configured with eslint to help you to write better javascript code and we all know we need all the help we can get when we write javascript so i'm going to install this as a developer dependency you know we don't need eslint running in production so i'm going to use the dash dash save dev argument and i want eslint and me personally i use eslint config reverent geek this is my own set of eslint rules that help me not only with you know some common mistakes that can happen with javascript but also the way that i like my code to be styled so you can have styling rules as well as coding and syntax rules so let's let that install and then next we need to install our production dependencies and first thing we're going to install is octa sign in widget and i'm going to specify version 4.2 and the reason i'm specifying a an exact version is i want you know as long as this tutorial lives on youtube which could be forever i want this tutorial to continue to work and the way we can make sure that it continues to work even though libraries can change over time is to you know start with a very specific version as of this recording so we need the sign in widget we're going to use axios which is a an api fetch library you know use it to call apis in this case we're going to use that to call our own serverless functions a lot of modern modern browsers have what's called the fetch api built in but just for compatibility reasons we may you know in case you want to build a serverless based application in the future and you want to deploy that and you don't know what kind of browser somebody somebody may be accessing your web application with axios is a kind of a fail-safe way of doing those client-side api calls and then we're going to install netlify dash lambda which is going to help us with our our lambda functions our i should say our serverless functions which under the hood um you know i mentioned before that netlify calls these netlify functions what what it really is is a wrapper around aws lambda functions you may have heard of serverless and you may have heard of the term lambda used those are kind of interchangeable as far as like that that the aws the amazon web server ecosystem goes so um if you were to create and deploy aws lambda functions which you can do there's a lot more work involved uh there's a lot of configuration a lot of setup and that's one of the reasons why netlify is such a great platform is that it takes something that's can be really challenging and hard to configure and set up and and makes it really really simple and easy so netlify lambda we're using 1.6 and then we're gonna also use parcel 1.112 parcel is a bundling tool uh you may have heard of a tool called webpack parcel is very similar to webpack uh has a lot of the same features but uh with webpack there's a lot of configuration again i'm picking a tool that is kind of the easiest to start with parcel without having to specify any configuration at all will kind of recognize the types of files and things that you have in your application and will package up your html and css and javascript and all the dependencies that are used by the by your application front-end and bundle those into a you know a lot of times it's a single javascript file that you can that will automatically be updated in your your front end code so great tool um also we're going to be using modern javascript in our front end you know so syntax like the imports statement and arrow functions and async and await which are great i love those features of javascript but again not every version every browser supports those features older browsers may not support things like async and await so parcel is going to do the job of transpiling our modern javascript into a an older syntax equivalent syntax that can run on across most browsers that exist today all right so let's install those dependencies may take a a minute or two i'm gonna take a sip of a hot beverage man mpm is amazing could have took a nap well that's the way it is with npm sometimes now there is one other dependency that we want uh another developer dependency something we don't need for for production and that is rim raff rimraf is a cross-platform developer dependency or utility for removing files and directories um and the reason we want remraf is as part of our build process so as we want to build a new version of our web application our front end code and do use parcel to bundle all that stuff up together we want to clear our distribution folder so in a nutshell all the code that we create for our front-end application it's going to [Music] get packaged and bundled and all those kinds of steps and put into a folder named dist for for distribution and um we're going to clear that folder out and before we start our build process all right so we've got our dependencies we've talked about what each of those dependencies do um by the way this video is based on a blog post that um i've written that goes through so basically we're following along with this blog post if you want to uh also pull up this blog post and follow along i'll link i'll have a link to it in the description below and you can pull that up in your web browser and you can kind of follow along with me and that way you'll be able to copy and paste some of the code instead of having to type it all in which will save both of us a whole lot of time because you don't want to watch me typing for hours and i'm sure you don't you know we're we're beyond those days of of of trying to uh you know retype all the code that we read in a magazine or something like that we live in a great age for computing all right so now i want you to open your project in your editor of choice and makes start making some uh some code changes so i'm going to use visual studio code and which i can call code from the command line which is really convenient if you don't have that ability to use code from the command line you can open up visual studio code if if this is what you're using go to view and go to command palette or shift command p one of the other and you can um search for shell command to install code in your path and that way you can call uh type in code at the command line and be able to launch visual studio code as your editor really convenient all right so right now we just have our package json file our package lock file and some node modules so i want you to open up package.json and look for this scripts and i'm going to remove the test script um and i i want to clarify or just state that testing is extremely important uh we're not going to cover any tests in this tutorial but um i've i've got another blog post on testing tools that are available for javascript and node.js i'll put that down in the link below description below and uh highly recommend checking out tools like mocha or jest that can add some test coverage to your application so the scripts that we want to create we want to create a dev script and this is where we'll run our rimraf utility on the dis distribution folder the dist folder and then at the same time after that command finishes we're going to call parcel to transpile and package up our the application and we're going to point it to the client folder index.html which we'll create in a little bit i also want to add a script here just specifically for build so in the uh for the build script we're also going to use rimraf dist and this time we'll call our netlify lambda and use the install command on netlify lambda and lamify lambda will find all the netlife functions that are in the project and set up any dependencies that they have and then we'll call um parcel build and that's that's the two we need all right now another thing that i want to add earlier i installed eslint and my own eslint config library i want to add an eslint con configuration file to this project so that esl knows how to use that in the project so i'm going to switch back to the command line and i'm going to create a file called eslint dot eslint dot rc rj i'm sorry i'm all over the place eslint rc.js now i can never remember the syntax well first of all if you're not on a mac or linux the if you're on windows that touch command is not probably not available unless you have the win the linux subsystem installed um so equivalent command for windows might be to uh like echo out a uh eslint rc.js and that will just create a blank file um touch is just a nice way of creating an empty file um where okay so i can never remember the syntax for what goes into this eslint configuration file and uh so one of the handy things you can do with npm is you can launch the documentation for any npm module using the npm docs command so npm docs and i'm going to pass it eslint config rev geek and that's going to launch a web page for the documentation for this module and i i know i have this one here that is like the the base configuration but i also have these alternate alternative rule sets and one of them is specifically for nodejs and that's the one i want to use so i'm going to copy that and go back to my visual studio code project and paste that into this module and one of the things that it's going to complain about is i need to declare use strict mode at the top of every javascript file in a node.js project this is just one of my personal things that i i like to do now now that i'm thinking about it this is going to be a front end project too it's not just node.js we're doing we're doing front end work really for the most part so maybe i need to switch to this browser version and that will be uh that'll be better um well we'll we'll see we'll see what happens later on maybe i'll i'll put uh i'll put this inside our client folder when we create that all right so the next step um we want to to cover is creating um our octa application that we need to secure uh everything that we're going to do going forward so adding security to any application such as account registration logins password policies uh profile management um you know email confirmations those kinds of things that's no trivial task and getting any of those steps wrong could have disastrous effects where you're exposing your your accounts or your client data to hackers and that's where a service like octa is makes your life as a developer much easier so to complete these next steps i want you to create a free octa developer account if you don't have one already and to do that you're going to go to developer.octa.com and click on this sign up button click the sign up button or click login and pause this video and come back after you've created your account intermission all right assuming that you have your account now i'm gonna uh and you're probably already logged in i'm gonna log into my account and you're going to click on applications click add application and then you're given a set of choices native single page app web or service in this tutorial we're essentially building a single page application it's just a javascript front-end to make calls to our apis so that's the type of application we're going to choose click next and then here on the application settings you can change things like the name and the base uris the login uri let's uh let's name this something like secure netlify demo or tutorial or what whatever i'm gonna name mine tutorial demo just to make sure that i'm not creating two of the same name i may already have one out there called netlify tutorial um and i want you to change the login redirect uri to remove this path implicit slash callback so it's just going to be the localhost port 8080 and you can come down here and click done and it's going to bring up this general settings page it's got information about your your octa project and i want you to copy the value that's in this client credentials box called the client id you're going to need this when configuring your application later alright so next step is to create a an environment file this is where we're going to store the configuration for our application create an environment file in your folder you can do this inside visual studio that's what i'll do i'll just right click here in this project folder and create new file and dot env is the the name of this file you need to create and in here we're going to have an octa client id and that's going to be the client id value that you just copied out of the octa application that you created so we need that value and we also need an octa org url where you find your octa-org url is go back to the octa developer dashboard click on dashboard up here to take you to the dashboard home page and your org url is in near the top on the right hand side of the page so just highlight that and copy it and go back to visual studio code or whatever your editor you're using and paste that in so those are the two values your values are going to be different from mine of course but paste in your client id and your org url now next we're going to build our client application so in the root of your project create a new folder named client and inside client create a new file named index.html and then i'm going to copy and paste in a bunch of well not a whole lot of html but a fair amount of html from the blog post that that we're kind of following along with this tutorial so just to walk through what's in this html it's got a doc type an html a head a title for this page which is secure netlify demo and then we've got a heading header tag and then we've got a couple of buttons defined here a a public button and a secure button they just have labels of test public api test secure api we will wire these up later in our javascript code same with the sign out button which right now has a style of visibility hidden so this sign out button will be hidden by default when the page loads we have an empty div tag with an id of results this is where we'll add messages and things as part of the output of our application and then we have an empty widget container div tag which we'll use to render the login form for the octa login and then we have a reference to an index.js file so inside this client folder i want you to create a file named uh site.css and we're just going to put in some very basic style um in here it's basically i'm going to copy and paste some code this is just setting the default font for our webpage to use arial helvetica set some margins and some padding it's just really really basic um css styling just so that it doesn't look quite as terrible and then the the big one is we need an index.js file so create an index.js and then i'm going to copy in quite a bit of code and then we'll walk through it all right so at the top of this i want to save this index.html file i forgot to do that at the top of the index.js file we have our import statements so we're importing in axios the octa sign in widget the octa sign in css file and our own site.css file and then we've got a couple of constants a org url and a client id now you need to change these values to match your client id and org url so even though we added these to our environment file we still need to chain also put these into the javascript file so i'm going to come over here to the environment file copy the client id paste that here and then also copy and paste the org url and now let's continue through this javascript and explain what's going on here there are comments all in the code that explain kind of each of the steps and what these functions do but we'll walk through it together so we have a display message function that takes in um any arbitrary text and displays that in the uh that results div tag that was that's in the html file we have a welcome message and that also enables the sign out button so we have an update this update profile function that takes in an id token and i'll explain tokens in a little bit but we're going to enable that sign out button set the visibility to visit visible and then display a message that hey are hello uh your name and and your email which are going to be part of that that token and then we have a sign out function that takes in the sign-in widget as a argument and it's going to you call some methods or some functions on that sign out widget to clear out any tokens and to sign out the current session and then it calls window.relocation.reload to just refresh the page we have a register events function that also takes in the sign in widget this is an async function so we probably have some await commands in here um so in this register button events we are registering the click events for each of the buttons that are on the page so there's a public button we're adding an event listener which is a click event and inside that click event we're going to fetch from our api our serverless functions api a function called public test and then display the results of that response in the browser using uh the data that's returned from that api and if there's an error we cache that error and also show that error message in the browser we also have the secure route it looks pretty much identical to the public one except we're going to use our access token to um to make that api call this is how you make a secure api call with with axios or or some of the other types of apis and that is to set an authorization header on that api call using the bearer syntax so we've got a header property with authorization which is equal to bearer space and then the access token which to us looks like a long string of gibberish uh but to a computer the access token is something that it can parse and verify and um you know extract information out of it's it's not encrypted but it's it's kind of like it's opaque to to us as as humans computers can interpret it though um and then we have our sign out button that just calls our sign out function we have a function called show sign in that's going to this render the sign in widget uh with our with things like our our octa client id and properties like the redirect uri so that it knows to redirect back to our local host application and you know sets a number of properties and sets a scope we want open id and profile and email scopes are like you know these are the things i want you to include with the response back from logging in these are all parts of the oauth and open id connect or open oidc standards um so you know everything that's that octa does is part of a an oauth standard that that's portable across any type of web application that supports oauth and open id connect we have a run octa login function which takes in that sign in widget and it's going to see if there is an active session like a session means that a person's logged in if that session is active then it's going to check to see if there are tokens in the url that you know what happens is um the login form goes out to octa you know same similar to if you're if you ever log into something and it's asking you to log into google or your gmail account or facebook you know those kinds of things that's that's kind of like an oauth login where it goes and logs you into this other service provider and then redirects you back to the application with your with your keys or your your tokens so that you can use the application and that's what's happening here is that when you sign in with the octa sign-in widget it goes and logs you in to your octa account and then redirects you back to the application with some information in the url is like query string parameters and so we can pull that information out of the url and be able to complete that oauth exchange by adding those tokens to our our application all right so we parse those tokens from url which completes that that oauth oidc cycle and we store the id token and the access token in our local token manager the id toke or the access token is the one that's important for security this is your this is your like your hotel key right that gives you access you know here's a card here's a token now give me access to the room that i'm supposed to have access to or in this case here's my access token give me access to the api that i that i should have access to the id token is similar but it also provides information about who the person is that log that is currently logged in um there are things like that person's name the email address depending on what claims as we talked about before were specified during the openid connect call to log in and then um so if we we after we make sure that we've processed any uh redirect um and we have our tokens stored then we're gonna get our id token and update the profile information one thing to note is that even even though we may have an active session perhaps you've logged in to your octa account and looked at the dashboard you may have an uh you know an active session but you may not have what this application is looking for and that part of what it's looking for is an id token and if it doesn't have an id token then it can still show the uh the sign in form so that you can log in again and get the the correct uh data that this application needs and then finally we have a document loaded uh event that we're listening on to it's kind of like your this is how we know that the web page has finished loading and rendering and we're ready to kick off our javascript code to to do all the things that were listed above so we're going to create the sign in widget and use like our octa org url and we're saying if we're going to turn on registration for this widget so that if someone doesn't already have an octa account as part of your application they can register themselves you know fill out profile information and get that that email verification and all those kinds of standard steps that go along with providing a a good web application experience and then we wire up our buttons and uh run the uh the login experience all right so that's that's a whole lot of javascript code that we've that we've gone through and i hope the the comments and everything are you know help to explain uh what each of those steps are doing and now this project is using what some people would refer to as vanilla javascript or plain javascript we could have used a framework like react or angular or view to do all these same things so instead of registering those button click events we could have relied on a framework like react or view to to do those things for us or even use something like jquery whatever tool you're most comfortable with um feel free to you know refactor this code to you to work with your tool of choice i will say that if you use a popular framework like react or view or angular we have octa-specific components that are available for those frameworks that you can plug in and you know make your life even even easier the main thing to understand is that from this front end code is that you're using the octa sign in widget to log in and receive an oauth access token and an open id connect token oidc id token and the access token is the key that allows you as the person logged in to access a secure resource such as an api and that's what gives you authorization to do that the id token includes information about your identity of the person that is logged in such as the name and email address all right as i mentioned before under the hood netlify functions are aws lambdas and netlify makes it so much easier to create and deploy and maintain these lambda functions one thing you need to know about serverless is the serverless functions are entirely self-contained and independent of one another and independent of the rest of the code that may be in your project that means if your function has any dependencies you have to install those dependencies separately from the main project you package as part of the the process of deploying you have to package up those dependencies uh during the build process and deploy them with the function the function code so the first step uh to doing this starting our serverless side of the project is to install the netlify cli tool so let's go back to the command line and there's two approaches the netlify documentation will tell you that you want to install the netlife cli tool as a global package meaning you can call netlify cli anywhere on your system at any time i tend i'm of the opinion that you should limit how many global modules you have installed on your system if if at all possible and with the latest versions of node it makes it possible to use a global type utility without installing it globally now if you're in if you're comfortable with with installing something globally then you do that by typing npm install g which is the global argument netlify cli and that would that would do the trick now you can call that function anywhere but instead i am going to install this as a developer dependency to this this particular project and this one this one's going to take a while um there's a lot in this utility this command line utility so i may speed uh speed up this process but i will definitely uh take another sip of a hot caffeinated beverage beverage beverage wow it is done and so i can call this function or you can call this function without having to install it globally using a cool new utility and that's included with node called mpx and mpx is like a node package executor i guess is what what the x stands for it allows you to execute any module anywhere from at any time but if that module is installed as a dependency locally to the to the project folder that you're in it's going to use the one that's already installed which is you know going to save a whole lot of time so um we're not going to run this command yet i'm just telling you what what's ahead all right so the next thing we need to do is add some configuration to our project that's going that the netlify cli tool is going to use to it's going to use this to create the functions and when building and deploying the application uh locally and building and deploying that application um into production in netlify nailify hosting so in the root of your project create a new file named netlify.toml or tommel i i guess you pronounce these as tamil files i'm not even sure what tommles stands for some kind of markup but anyway and then switch over to visual studio code open up that netlify tomml file and i'm going to paste in some configuration here so we have three major sections of configuration there's a build a dev and a redirects so the build section specifies the commands and configuration for building and deploying the netlify application so the command to build which is npm run build we defined that in the package json file uh we're telling it that any netlife functions are going to be found in a source folder under functions we're specifying that our node environment is version 12 and that our publish folder is what we want to publish when we deploy the application is going to be a folder named dist our distribution folder for development environment things we're specifying that the port we're going to use is 8080. again the published folder is the dist folder and the command to run our development environment is npm run dev which you know we also uh defined in the package.json file and then finally we have a redirects block that is telling netlify when netlify builds and deploy netlify functions by default they are at this path slash dot netlife functions and you know that works but it's kind of kind of ugly but what you know thankfully we've got a way using these redirects to use whatever path we want so if we want a path be able to call a local host colon 8080 slash api whatever name of our serverless function is we can do that and it's going to map that call from api to the actual underlying path which is dot netlife functions and that's what we need so the next thing we're going to do is use the netlify command the netlify cli tool to create the functions that we want so i'm going to use mpx netlify functions create um specify a name of public dash test all right and i get a warning or an error message that the functions folder specified in the netlify tomml file is not found so we we're looking it's looking for this source slash functions which we haven't created so i can either use the command line to make that those directories here or i can switch over to visual studio code and and make those uh folders here so i'll say source and create a folder underneath source called functions all right now let's go back and try running that command again this time we get further um it's asking us to pick a template what kind of serverless function do we want to create and there's you know lots of examples that that we can choose from as kind of like a starting point in this case let's just choose hello world um a a basic uh hello world function serverless function it's now been created if we go back to our project we'll see that we have a a public test folder and under public test we have a public test.js file and this has all of our the the basic javascript code now eslint is complaining about a number of things because it's not formatted the way that i would normally want to see things formatted if i just resave that file and it's going to clean some of that up all right so that's the that's the public one we also want to create a secure serverless function so let's uh use the same command and we'll name this one um secure dash test again choose hello world and before we go any further as i mentioned before if if a serverless function has needs a dependency of any kind that has to be set up installed separately or copied into that project folder separately because serverless functions are independent from everything else including other serverless functions in our secure test uh function we need to be able to verify the access token that's being passed to know if the person who is requesting that api is if that token is valid and if that person is authorized and we're going to use a tool to help us call the jwt verifier so you from the command line change to the source functions secure test folder and use npm to first initialize that folder so we get our package json file and then use npm install to install octa jwt verifier version one all right now we need to update our project with some code so in the functions secure test open up that secure test folder and open up the secure dash test.javascript file right now it's just the hello world javascript code i'm going to delete all of that and paste in a code from the blog post that we're following along with so this code and it's re it's complaining about some things i'm going to go back excuse me and in the eslint rc js file that we created to begin with i'm going to change this back to node instead of browser that'll just make me feel better so oh in our secure.js secure test javascript file we'll walk through this we're requiring in our our octa jwt verifier uh module that we uh installed as a dependency we have a function called verified token verify token it's an async function that takes in the auth header from the request that's that's coming in to the api and it splits that off header uh on a space so if you remember this the standard syntax for um passing a token to any res http resource like an api is to use that bearer syntax so it's like your off headers are equal to bearer space and then the token so what we expect is that when we split that header on that space that we're going to get two parts and the first part is going to be equal to bearer and the second part is going to be the token so we expect to have an access token if there are if there aren't two parts and that first part is not equal to bearer then we're going to return null which you know to our code is going to indicate that someone is trying to access this api and they're not passing any access token at all which is a no-no right because we want this to be secure um so we're going to take the access token from that second part of the authorization header and then we're going to use the jwt verifier with our org url and the client id these are being read from the environment environment and we're going to call a verify access token passing in the access token that was sent as part of the request on the authorization header and this default scope of uh api default and if everything went went okay then it returns the parsed json web token or jwt um as as i mentioned before access tokens id tokens um oauth open idc uh open oidc uh these tokens are the format of these tokens are json web tokens and json web tokens is just a standard way of packaging up um information and they can they have a what's called a cryptography a cryptographic signature and that signature helps uh the verifier to know whether or not that token has been tampered with since it was originally issued by the authorization server so an authorization server when you log in it it provides that access token generates that access token and provides it back to your your client side code and if you try to do anything with that token if you try to insert more data into that token or or try to falsify that that token the verifier is going to know that that you've tampered with it also inside a jwt is things like an expiration date so json web tokens don't live forever uh they're they're relatively short have relatively short lives and that's another you know security standard so if a token is expired then the verifier is going to reject that token and whoever's using that token won't have access to that resource until they get a new access token all right so enough of that so that was our verify token function and then the magic for a serverless function is the handler so the standard syntax for the handler is it is an async function it takes in an event and a request context which we're not using the context in this example but the context can include things about the request maybe some data that was passed along or um or whatever so it the jwt we're going to call uh verify token passing in the event dot headers dot authorization so this is like the the request that's come in and if we got nothing back if the jwt is null then we know well maybe there's there's either a problem with the token or maybe there was no token at all so we're going to return uh 401 which is the status code for not authorized and with the text you are not authorized to access this resource but if everything was good then we're going to return a status code of 200 which is the ok status and with the headers that are the content type that we are returning is application json and the body of our response is going to be a message a json or a javascript object with the property of a message that has hello and then we're passing back uh a claim that's embedded in that jwt so the jwt that was parsed that's that's the access token it has some you know some basic information in it and we can pass that back from the api now normally i'm not doing this in this tutorial but you would take that access token and perhaps make additional calls to other apis or or to use that use that access token to make um calls to an internal service or uh maybe a database or or whatever um that access token can you know be passed along to make other other calls to other things uh within your the architecture of your application so that that those things know who who that person is that's requesting the information all right so i think we are now ready to test everything that we've done so far so let's uh let's close all these files and let's open up go back to our our terminal and change back to the root of our project and let's call npx netlify dev and this is going to i think i have something else running let's try that again it's going to spin up a local development web server and it's going to host the netlife functions locally so that we can test those functions locally it's going to call those build commands such as clearing the distribution folder calling parcel to package up our html and css and javascript and all that kind of stuff and deploy it and it now says that the server is ready on localhost 8080 and parcel has built our application now before we open up the browser just wanted to show you if you go back to visual studio code or if you want to you know look at it some other way you'll see that you now have a folder in the project called dist and you know it man it stuck a whole bunch of stuff out here in this folder that's because it was able to package up all those dependencies all the files that are associated with those dependencies uh like the css for and resources for the octa sign in widget and yeah just tons and tons of stuff that's now part of the our web application that that our application depends on um so that's going to get cleared out every time we we rebuild our our project and you know parcel is going to create all that stuff for us again so open up your browser and go to localhost 8080. now i recommend to get like a true end-to-end test that you uh launch a private window uh private browser instance so i'm gonna do that i'm gonna open up um an incognito browser window and go to localhost 8080. one thing to note is chrome has added if you're using chrome chrome has added this function or this option down here and it may be turned on by default but it says block third-party cookies uh if you turn this on right as as of this recording it's going to break um the octa-sign in so you need to allow third-party cookies uh in order for the session system the cookies that that octa sets when when you log in to work correctly so make sure that if you're going to use an incognito window that you have these third-party cookies enabled or it's not going to work all right so you should see what i'm seeing netlify function tester we've got a couple of buttons up here and then we have our sign-in username password and then there's also a link down at the bottom that says if you don't have an account then you can click sign up so enter your octa developer account credentials the same ones that you use to create your your octa developer account you can also create other logins you can also use the the register function to create a whole new login if you've got a different email address and if all goes well it's going to sign in and you've got you know it went very very fast but you may notice in the url that you know the url was full of stuff at one time and now it's not anymore those those are like the intermediary uh code and temporary tokens and things that the login needed to complete the oauth and oidc um authorization process so now we're we're logged in we see a new message hello and for me it's hello david neal and my email address and that's pulled out of the id token that was part of oidc and then we can click test public api and we get a message back hello world as we would expect and that's calling our local functions and then test secure api it worked if everything goes well and you know you're signed in you've got your access token it can call that secure api endpoint and verify the token and respond back with hello and one of the claims inside that access token is it's called sub that that stands for subject and the subject of that claim or the subject of that access token is you it's your id your in this case email address and then finally we have a a a sign out button and you know we get our form again to log back in it clears the login session and we're back to the beginning sweet everything is working and going to plan here's where i would insert a animated gif it's working yes success i hope you're having success as you're following along this tutorial so now we've got our application working locally what do we what's next well the next step is to set up continuous deployment with netlify we want to we want to deploy this thing into production and to do that uh let's create our netlify account if you don't have it already go to netlify.com up for your account but the first step to get this to work like we want it so that every time we make changes to our code that code gets redeployed through netlify automatically we need to put all this code that we've created so far into a git repository that netlify can access so netlify supports uh github and git lab and bitbucket and you know maybe some others which all have free editions of public get repository hosting i recommend that you pause this video and follow along the instructions that that are provided by your get host of choice to create a new repository for your project and maybe you know make that that first step whatever you're comfortable with and come back i am going to go to my github account and i'm going to create a new repository and i'm going to call it secure netlify demo which is available i'm going to make sure that it's public now netify will work with private repos too um through uh you know your authorization uh you can granted access to to view your uh you know your repository i'm going to create this repository and you know when you create a repository in github it gives you another a number of steps that you can use to initialize your project so i'm going to follow kind of these steps right here from the command line so i'm going to come over to here press control c to stop my local development server i'm going to use git init to initialize an empty git repository and one thing that i want to make sure is that not everything that we have in this project is something that we want to commit to our repository specifically like the like the env file uh that is that is environmental specific configuration specific to like my local development um you know it may you you may have some secrets in that file at some point that you don't want to commit to a repository so i'm going to create a get a dot get ignore file and in visual studio code i'm going to open up that gitignore and copy and paste in some stuff here so we don't want to commit our entire node modules folder to our to source control um that's that's bad uh we want to ignore our env file and then you know just anything else that might might show up we don't want to commit our distribution folder either because that's going to get created and at every time we deploy or netlify is going to run our deployments on their system to set up um the dependencies and everything to deploy your project um let's see so back to command line we we ran git init let's add a get remote add origin and then the address for your repository i'm going to add my repository paste that in there and then i'm going to get add everything if i look at get status which i always do is kind of like a sanity check make sure that nothing that i don't want to deploy is getting getting deployed that all looks good i'm going to commit that as a an initial commit as the message and then i'm gonna get push with a dash u so the first time you push to a new like we set up a remote to your repository and i i'm using my repository dash u is going to tell get to use that repository or that that branch from now on uh to push things to so anytime we type git push without any parameters or additional arguments it's going to push the current branch to production or to the main branch all right now that we've got that code deployed or that code committed to the repository we can go back to the repository refresh here everything's good everything was committed a minute ago now go over to netlify and log into your netlify account if you're not already logged in i'm gonna log in with my github account and i've already got you know some other stuff sitting out here but you want to click new site from get and as i mentioned before it supports github get lab and bitbucket i'm going to click on the github button because that's what i'm using and it's going to it it popped up a separate window to authorize my github account which i've already done before so that that only took a second went away it might take an additional step for you to log in and grant access to um netlify to access your uh repositories that in itself is an oauth flow where you're logging you're using your credentials with github and you're granting um netlify a specific set of privileges um it's you know under the covers it's using oauth to create that that access token that it's going to use to make api calls um to your your git um repository pretty cool stuff um anyway i've got a whole bunch of repositories sitting out here i don't want to browse through them so i'm going to say search for secure and there's my secure netlify demo that we just created i'm gonna click on that one and then um let's see what else one thing we need to do is we need to do a couple of advanced steps so everything else is fine it picked up from it it actually read the netlify tomml file from the repository so it knows that the build command is npm run build and the publish full directory is going to be the dist folder but under advanced is where you define environment variables so so since we are not deploying the dot env file we need to set environment variables for this particular application so click on new variable and i'm going to just pop over to visual studio code and open up that environment file and so we want one called octa client id so the this could change you know like if you wanted to have a separate octa application instance for local development and another one for production this is where you know you would this would be different for your environment i'm going to create another new variable and that's going to be the octa org url and now we're ready to deploy all right so the name of my application is fervent turing d1d536 i'll commit that to memory yours is going to be different um but the cool thing about netlify is it creates these kind of placeholder urls that you can use to view your application so while it's building let's see what else we may want to do when this is done it's going to generate a url for this website and before we can actually test this application we're going to need to let octa know this new url that we're using so let's see how far along we are so i think if you click on the site deploy in progress you can actually see you know a little more details you can drill down into um and actually see the build process and everything that's been going on so i think it's done mine is let's make let's see it still says it's in progress time for another sip of a hot brevid what did i say and there we are nellify has deployed our application i just needed to have a sip of coffee um so here's our url we need to let octa know that we're using this new our new url and to permit this new url is as part of the login process so right click on this link and copy that that link address now go over to your octa account and click on applications go to the application that you created for the this tutorial click on the general tab and you know we've got all our settings we've got things like this login and stuff click on this edit button and we need to add some uris so that octa knows these are valid so on the login uri paste in that new url and for the log out do the same and then we also need to change the initiate lock you don't have to but i'm going to go ahead and change this initiate login uri this this should be whatever your production site is not localhost so this is fine and let's click save all right now there's one other thing we have to do with octa and that is to add this site as a trusted uh origin this is the terminology that uses so um octa knows that if a redirect comes from this site it's it's okay it's it's expected so click on go to ap the api menu click on trusted origins and here click on add origin and we'll give it a name like netlify secure serverless tutorial um the url for the app and we want to allow cores and redirect and click save cool so now if we were ready to test so open up another browser or open up a let's open up a an incognito go to that url sweet we got um our buttons and now we got our our login showing up here let's try logging in boom it's it's working it's working test the public api hello world now this is this is uh calling netlify functions this is going often and uh executing a function that lives somewhere else in the cloud this is an aws a true aws serverless function so the public one works the secure one works and then we can sign out if we try to call secure api function when we're not logged in it tells us we're not logged in we can't use that we can still hit the public one though sweet sweet sweet all right that is it oh except maybe we want to make a change and um yeah we want to see that we can deploy a new version of our application within a minute or two which is you know one of the beauties of working with serverless functions so we're working with netlify so let's go make a change to the application whoops don't know what's going on there but don't save that um let's go to our functions maybe the maybe the secure test and change the message from hello whatever this is to hello period it's working maybe change something on the home home page too uh let's see so go to the client index.html file add another something here let's just call it hey y'all so go back to the command line we do get status we should see two files have been changed let's uh add those two files commit them to um the branch just call it changes for the demo and then let's push pushed to the git repository and now if we go over to our um netlify account let's see maybe re go to the deploys tab look you there it is now building a new version of the application and it has the commit message that we that i put in there changes for the demo and if i want to i can click on that and i can actually watch the deploy happen um uh which should be about none still says this building it's probably packaging up those uh those functions let's go back and look at that again so let's run an mpm build i think what it needs is another sip of coffee there we go now it's created all these distribution files all the way down and now it says the site is live so let's go back to the incognito window that we had opened earlier i'm going to refresh this page looky there hey y'all log in again whoops helps to type in the correct password test our secure api it's working yes well that is it we've done all the steps all the things that we've set out to do um i hope that you've enjoyed uh creating this learning how to create secure serverless functions using netlify as i've said before netlify makes deploying applications so easy octa makes adding authentication and authorization to your applications so easy than having to do these kinds of things on your own um so again i'm gonna post some links to some resources into the description below and as always you don't need permission to be awesome you get out there you take this stuff that you're learning and you do some awesome things with it i would love to hear your feedback if you have any comments or questions leave those down below and until next time hope you have a blessed day see you you
Info
Channel: OktaDev
Views: 1,213
Rating: undefined out of 5
Keywords: netlify, node.js, serverless, faas, oauth, oidc, okta
Id: J2DV_H23lEs
Channel Id: undefined
Length: 97min 49sec (5869 seconds)
Published: Tue Jul 14 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.