React Native Login with JWT Auth Context

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone what's up Simon from galaxies.dev back with a new tutorial on react native today I recently tried to implement a JWT authentication with react native and it actually wasn't too easy to figure out the right steps but once I had it everything was super easy so I'm gonna walk you through the steps of creating an authentication context and provider working with the API with a login and registration functionality and how you can use the Expo Secure Storage to manage your JWT and store this in a secure place if you want to check out the code link right below the video and definitely also check out the rest of our courses on galaxies.dev which is all about exploring the edges of the web dev universe so make sure you check it out hit the like And subscribe button so you don't miss the future videos and now without further Ado let's build our react native app alright so let's get started with the app I'm gonna start with the typescript template of Expo because well we should just use typescript at this point and then I installed a few packages so I installed axios I know you can basically use fetch these days but with axios you can actually easily manage the header and we're gonna later have to attach our beera token to the API calls so I'm going to use axis in this one also I install react navigation because then we can have a little stack navigation and switch between the login page and our inside page and for that we also need to run Expo install Rec native screens right native safe area context and finally we're gonna add the Expo secure store so that is the most important part probably because this is the package that we're going to use to actually store our JWT once we get it from the API and to use that there's actually a little block here for the configuration that we should use so in our app Json under iOS config we should use uses no I think we actually need the full config block let's check this out uh iOS yes there's not even a config blog so let's put this into our config uh for Android I think there's no other usage and we will see it basically pretty easy we can just set items and get items in an asynchronous way we just have to make sure that we're using async await but that shouldn't be a problem for us right so with that in place uh we can already run npx Expo start and we can run this on the web do we want to run a web or iOS let's go for iOS today there we go our preview okay so this is going to be pretty boring so far and what we're going to do now is we basically want to create a login page and an inside page and that inside page needs to be protected so in order to protect that page and to have this logic we're gonna add contacts around our app for our authentication and that context will be well where do we want to store this let's create a new folder I love it that Expo that Visual Studio code is not doing the folders for me I really hate this so I'm gonna do app context by the way you can actually have a slash in there so it generates I could even have done this for the file by the way um so I'm going to call this auth context.tsx and then we're going to get a bit more space here and that let's begin by a few Imports and an auth props interface so that's going to be the interface of our provider that will make it a lot easier to interact and get all of the information we can actually put this to the side we also import the Secure Storage and what I also added right to the beginning is um hello oh I love it when my keyboard is not working anymore um a key so this will be the key under which we're going to find our JWT or whatever you want to store in Secure Storage the API URL I'm just going to use my own API at api.develop Adder apps you can also do this for testing you can check out the documentation here pretty much what we're going to use is a post to users to register a user and a slash auth to get a JWT and then some of the other calls just to test if we are allowed to make a request by the way you can also run this locally you can find all of this on galaxies.dev in the tutorial link below this video so then we're going to add our auth context um an easy export so we got our use of that we can import just like a hook in our pages and then the actual const auth provider begins um just the default setup for context I'm gonna just add any in here and then this provider will manage a few things um but most importantly in the end we're gonna return this object which wraps the context around all of the children and now we just need to make sure that we Implement all the functionalities and also cover the state so the state in here is our auth state it will be either um null so this would be the initial case as we initialize it with that or have some information about the token and the flag for authenticated so looks more complicated than it actually is it is just a state now we need two or maybe we need three functions in here we need login we need register and we need sign out so we got the whole flow from our login page to the other pages so let me bring them in one by one we're going to start with probably the registration uh because that's actually the easiest call so to register our users we just need to make a post request using axios to our API URL slash users and pass the email and password to it nothing else a standard registration and by the way everything that we do goes to our value here we just need to make sure that we follow this interface so we need to call this on on register register and then the value would be happy now once we log in it gets interesting because in the login case uh let's get the grab this we can pretty much start with that again so we need email and password again for the login we're making a post request to the auth endpoint this time and now once we get back the data here I'm gonna first of all update our state so I'm going to say Khan's result in this case because we're actually interested in it we gonna add the total that we get back from the API to our state and we're going to say okay the user is now author authenticated and you can already imagine that in the end we're gonna do the opposite we lock all the user we're going to reset that back to zero now the important part of the JWT authentication is that you're gonna attach that header or the key or the token or whatever you want to call it to all the future requests that you make to the API to show that you are authenticated and we can do this by using axis and that's why I installed it in the beginning this is a bit harder with fetchum to implement an Interceptor with XCS we can just say default headers common equals this and then for every request that we do with xcos our totem will be easily attached and we can also have more sophisticated logic with axis but that is basically everything that we need um or at least for my API if you have a different API that you're using make sure some expect to some expected in a different way but usually it's in the authorization header and then beera and the token now what we also want to do of course at this point is store the total so we got it next time when we start the app because it might still be valid so we now use the secure store from Expo and say set item async and to this function we're going to pass a key which we defined up there because I don't like to have strings in here I don't want to make a typo and then I I'm not loading the key or I'm not setting it correctly so I'm going to use my cons here and then the value is of course result.data dot token cool and then we have stored this and we can just return the result to whoever is interested in this otherwise uh we can just return our error again and that's pretty much it now once we want to log out the user we just need to do the whole opposite of this we don't need to make an HTTP call by the way to the API that's not required but what we need is delete the item reset the header and then reset our authentication state so once we got all of these three things in place the user is pretty much locked out and at the top level of our app we're gonna check for the authentication state so if the state changes we're gonna automatically render our login page instead of the inside area again and now we just need to make sure that we're actually putting everything in here so on login um on logout uh log out and then we also should have the auth state in here perfect now there's one more thing that we need to take care of and that is once we start the application so we are writing the item to storage where um we're not loading we're deleting it but we are not loading it so let's add a use effect to our auth provider which will be called right when our application starts so there we go oh it's hard to to have the right amount of brackets oh God damn I should just okay second try um we don't have any dependencies for our yeast effect today uh we're just going to implement a load token because that's going to be an asynchronous function and I'm just going to call this afterwards from here so that's the setup we want to have and now what we need is of course grabbing the token from our Secure Storage so on load we check is there a totem and if we do get back a totem um let's put a little lock in here so we can later see this uh stored token and if we do have that total we of course can just say okay then we're going to use this for our headers and we're going to also update our state with that information because then we can immediately log in our user and with that set up you have done 99 of the work for building a JWT of your react native application now we just need to put this to work but that part is going to be pretty easy so let's move over to our what are we going to move oh we probably need some pages um so if we need Pages let's create a new folder I'm going to call this greens I'm gonna do a new file login.tsx and also home.tsx so react native functional export regnative functional export component so those pages will be implemented in a second for now we just need like the dummy implementation and we can heat over to our ftsx which is currently the entry point and now it begins we're gonna wrap our whole application in the just created of provider and now we can have the stack and screens in here but I kind of like to have like my own little layout and we could probably have this in a different file but for now I'm just going to do it in here so I'm just going to call this layout and then we're going to use the navigation container to build our navigation so uh navigation container that will be wrapped around everything and in here we're gonna have our layout great now we just need a bit more for the layout of course so if we want to create the simple push stack navigation we're going to use create native stack Navigator so that is our stack and within the navigation container please put the brackets around this come on um inside of the navigation container we can now say stack dot Navigator and within that stack Navigator we're gonna Define the different screens of our app so as we want to make this dependent on the authentication State we're gonna now use our hook that we added which exports the auth state and on logout we're gonna get this from use authentication so that is also why this statement can't be up here because then we don't have access to the authentication provider yet the layout is a child of the auth provider so we can actually access it through the context that is the important part here to make the logic work and now we can say okay what's the auth state DOT authenticated if we are authenticated we're gonna of course show the inside area in my case that's just the um the home component so home component would be home I'm sorry please add the import there we go um and in the other case which means we're not authenticated uh we're gonna use stack dot screen and that is gonna be the login and also component log in okay so uh still an error message uh if you actually yeah we probably need to restart Metro also can you please just not put this on one line that looks horrible nobody can see this uh there we go okay additionally we probably want to have for the home page a little button to lock out the user so you can do this with the navigation uh by just setting the options uh to an object and then for header right we can pass in a button or whatever we want and the cool thing is at this point we have the unlockout function so we don't even need to do some manual injection or whatever in the uh inside page we can just do this from here and manage everything from here and really this line is all the magic we need to protect our app so let me save this and then I probably I probably feel like we should I should probably have just I could have probably just press restart that would have been enough um but anyway now we restarted and everything should come together but of course we don't really have a lock-in screen so we should focus on that and quickly Implement that so for the login what we need is of course two input fields for email and password and we're gonna also get on login and on register from our use of hook um is it already starting uh let's see again let's refresh yeah here's the login page that's good that's good news uh we're on the right track now so the cool thing is because we have the API calls and the token handling all inside of our provider our functions here for the actual login and registration are pretty easy because we just need to call on register or unlock in with email and password and then either show a result or pretty much do nothing because that will update the auth state and our app our auth state will automatically switch to the login area um additionally I made a little change here so automatically after register I call log in because my API has no kind of um like verification of the email so with that in place let's quickly build our login view um for the view we definitely want to have some kind of styling so let's put this here and I'm gonna add can you please import the style sheet no of course you can't why why should you uh so let's go to react uh actually to react native text doesn't exist oh yeah yeah text I'm not using text anymore text is uncool uh for the view so I'm going to use a simple view let me bring this in because it's actually going to be quite boring it's just a standard view setup but of course I should put some brackets around this and I'm also going to add a few Styles and then I'm going to walk you through what we just did here so here we go um simple container the first contain do we actually have a container styling yeah we just align all the items in the center for now I'm going to use a little image from galaxies up here it's of course not something you would display in your application and then our Forum here has a little gap between the elements and using 60 of the width we get the text inputs uh on change we're gonna use set email or set password and for password we've also set secure text entry to make sure that this actually looks like a password input cool um besides that we have our two buttons for login and registration and we can even try that so sign in uh alert user not found so that's good we're getting the alert message from the API here create account uh can't create user with those credentials perfect that's perfect that's exactly what we wanted to see um can we can we try let's try something so I'm going to add a use effect here to make a simple API call let me grab the auth context um let's do something like get all users we're gonna try this uh const test call I think so this is just a verification uh that our stuff actually works uh we're gonna do this we're gonna come on just the whole world uh test call and no dependency so what we want to do is we want to check if we can get a result right here on this login page and I highly doubt it because let's see where are we axios request failed with status code 401 which basically means we are not authenticated to make this request and that is good news because that means we're trying to access something from the API but we're not allowed to do that so now let's create an account I'm gonna use uh a add a that D whatever and then a super secure password okay create account uh can't create users it's my password account does my email have to be like lowercase or something I don't know and why is the first letter always uppercase I don't want that can you please just make it lowercase I'm just gonna do PNP dot d e uh oh yeah that account already exists I'm using the real API not my local API right uh let me quickly switch this I'm gonna go to localhost 5K there we go I should still get the same error yes I do but now I should be able to actually create my fake account nice there we go that was my fake account sign up um should now be able to go back and I should be able to use my login now so we've seen before that login did not work but now login should actually work so let's see yeah there we go uh we also get back the what is this auth context 41 what did we lock out here uh 41 I don't actually no the store token probably uh no that's actually not the star token but anyway it did look something now the interesting question is if we put the call we got here on the login screen now into our home screen would we see a result hmm and I actually hope so because otherwise our whole authentication did not work so let's hit save and I don't want this lock where is this lock coming from uh login 16. oh it's still calling the stuff here can't comment that and on the home page I actually want to have result.data so this is it we are getting datar here on the login page so if we wanted to make this simple um I could change this view now to be something like this um so with a little use state for users then I'm calling all the users and then I'm displaying them in a list I actually only have one average yeah I did set the key each child launches a list I should have a unique key oh yeah it's underscore ID I'm sorry that should fix it but if I would change this and I could now hopefully kill this did I kill it and then go back to Expo go open the app again and we've seen we're shortly on the login screen but then we're retrieving the token from storage and we're automatically logged in because of the logic we implemented in our app.tsx and that is pretty much everything you need to make this work and I could now switch this out easily from localhost back to the real API go ahead and sign in if that account still exists I don't know uh and they find yeah probably that doesn't exist I don't know what my account was uh was it like this.com [Music] oh man I think I had an a at a dot d e I don't know why it's making uppercase uh please Apple simulator could you just stop that I don't like that because my API uh might check that oh come on I'm really not allowed to do anything in here well uh if you have an account for the API which you can create for free by the way um just use it as described in here it's not a problem we are also using this in most of the courses I don't know my uh API not develop betterapps.com um probably I should just have restarted my application um yeah we're getting into a lot of trouble here um let's do this one final time yeah well looks like today I'm not allowed at my own API to log in but you're gonna have more luck so with my local API it did definitely work better uh probably there's something but there's a problem right now with the API I'm gonna check that out but right now we have the perfect starting point for your react native application with JWT login this auth provider and the context we're wrapping around the app is really everything you need to check we are listening to the well listening we're reacting to the authentication State and either display our home screen or something else and this could of course be another layout or another stack navigation so if you have in the inside Area tab bar or something else you could also just have that in here and with that we're finished with our react native app for today I hope you enjoyed this quick run through of how you can add your JWT authentication to your react native application it really comes down to the provider and having the authentication State at the top level and then managing the different routes or navigation mistakes in your app and really that's it it's not too complicated once you get that setup in place so I hope you enjoyed it again code on galaxies.dev which you can check out below and of course hit the like button and stay subscribed for all the future videos I hope you have a great week with awesome code and I will catch you next time so until then Happy coding Simon [Music]
Info
Channel: Simon Grimm
Views: 35,569
Rating: undefined out of 5
Keywords: cross platform, hybrid app, javascript, ionic academy, capacitor, web development, mobile apps, mobile app development, react native, jwt authentication, expo, react native navigation, typescript, flutter vs react native, react native vs flutter, react native ui design, react native ui, react native expo
Id: 9vydY9SDtAo
Channel Id: undefined
Length: 24min 59sec (1499 seconds)
Published: Tue Mar 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.