how to use JWT token in Angular 17

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
are you tired of dealing with authentication headaches in your web applications imagine a world where securing your angular app is not just easy but also robust and scalable that world is here thanks to jwd tokens hi I am Aya zafer and I bring to you years of experience in web development with a special focus on angular over my career I have faced numerous authentication challenges from simple logins to complex secure access mechanisms and Time After Time I have found JWT or Json web tokens to be true Game Changer today I am excited to share my insights and experience to help smooth out your development journey in this tutorial we are diving deep into how to effectively use JWT tokens in angular 17 we will start by understanding what JWT tokens are and why they are the go-to choice for authentication in modern web apps next I will guide you through setting up your angular project and implementing JWT authentication from scratch we will cover everything from creating an authentication Service managing token storage to protecting routes with gods and handling token expiration whether you are just starting out with angular or looking to level up your authentication strategies this tutorial is packed with practical insights and real world applications so let's get started and unlock the full potential of JWT authentication in your angular applications make sure to hit that subscribe button and turn on notification so you don't miss any part of this comprehensive guide so let's Dive In before we dive into the code let's lay the groundwork by understanding what JWT or Json web tokens really are Imagine jwd as a compact self-contained package for security transmitting information between parties as a Json object this information can be varied and trusted because it is digitally signed a JWT is composed of three parts the header payload and signature the header typically contains the tokens type which is DWT and the signing algorithm being used such as hmac s a256 r RSA the payload part holds the claims claims are statements about an entity which could be your user or additional metadata this is where you put the information you want to transmit like user ID and permissions finally the signature ensures that the token has not been altered it's created by encoding the header and payload with a secret key this makes JWT is secure and temper proof so why use JWT for authentications first they are stateless the server doesn't need to keep a record of tokens each JWT contains all the necessary information within it this makes scaling your application simpler they are also secure offering strong mechanism to verify authenticity of of the data and lastly JWT support scalability and flexibility easily fitting into different types of authentication scenarios now that we understand jwt's let's start by setting up our angular 17 project open up your terminal or command prompt and let's kick things off with the angular CLI just type the command NG new and your project name we are creating a new project named project name you can set whatever name you prefer you should also select the routing option and also scss for styling hit enter and wait for the magic to happen with our project scaffolded it's time to add the necessary dependencies for handling JWT tokens we'll use the ozero angular JWT Library a popular choice for integrating JWT authentication in angular apps so let's do that I already have installed my project and it is currently open in my vs code and it is running in my browser it is simple just a starter project with the hello word message and nothing else so open up your terminal now we can run the command npm install at AU 0/ angular D JWT press enter this command installs the oz/ angular D JWT package into our project it provides a set of tools to handle jwt's like automatically attacking tokens to requests and handling token storage with our project setup and dependencies installed we are now ready to start coding our authentication system next we will dive deeper into creating an authentication Service managing jwt's and securing our angular routes you won't want to miss this with our angular 17 project setup it's time to roll up our sleeves and Implement JWT authentication this Cornerstone of our authentication system will will be the Au service which handles login log out token management so let's Dive Right In first we will create an authentication Service this service will communicate with our backend to authenticate users and store the GWT token received upon successful authentication NG generate service o this command generates a new service named o in our project now let's open the o. service.ts file and start coding so here first of all I will Define some properties of this class private read only JWT token is equal to JWT token and then private logged user string then private is authenticated subject is equal to new Behavior subject Boolean false okay make sure to import the behavior subject from the rxjs make it optional now we need to inject the HTTP client service for that I will use inject actually let me Define a property first HTTP is equal to inject HTTP client I don't need uh the injection through the Constructor because I'm using latest version angular 17 so it will work in this way as well now let's create a function login that will receive a parameter user of type object that will have properties username string and password of type string and it will return return a type of observable any and now I will return this. HTTP dopost /i/ Lo [Music] login and I will add pipe to it and I will pass some operators Tab and in that I will pass a call back function that will receive a parameter with the names token and I will call a function do login user and then I will pass the username and tokens that I will receive from here now I will Define a function private do login user username string tokens any and then I will set this. logged in user is equal to username and I have called the next function on the behavior subject that is is authenticated subject and then I will use actually before that I will do this. store JWT token tokens. JWT we need to Define this function to save the JWT token will also be private store JWT token and then I will save it in the local storage by use calling the function set item passing the jwd token and so this is the name of the local storage and this is the actual JWT okay next I will Define a function log out and then I will remove the local storage and then I will call this dot is authenticated subject. next false this time I'm sending false instead of true okay so here we have created a simple login methods simple login method that sends the users credential to the backend and stores the JWT token upon successful authentication we are using local storage to prist our token though you should access the security implications based on your application's need when it comes to storing jwd tokens there are a few options local storage is simple widely used but the mindful of cross site scripting attacks as a safer alternative consider using HTTP only cookies or other Secure Storage mechanisms especially for highly sensitive applications like we will set up an HTTP Interceptor to attach that jwd token to every outgoing HTTP request this ensures that our backend can authenticate the user based on token in each request so now we will generate the Interceptor by running a command NG G space Interceptor space Au press enter after generating the Interceptor let's implement it so go to that so first of all I need to get the jwd token so I will Define a function here get JWT token so here now I will written the actually let's add function before it okay okay so now it will give me the token from the local storage I will save it in JWT token is equal to get token okay now I will check if jwd token is found then I will use request do clone and set headers and pass a custom header authentication beer jwd token okay so in this way whenever a request goes to the back end uh it will automatically check for the token in the local storage if it is found then it will attach with your HTTP request every time this Interceptor checks for a jwd token in local storage if it finds one it clones the outgoing request to include the token in the authentication header authorization header this is crucial for ensuring that that your requests are authenticated and authorized by your backend with the Au service and Au Interceptor in place our angular app now has a robust JWT authentication system we can authenticate users securely store tokens and ensure that each request is properly authenticated so far we have laid out the foundation for a secure and scalable authentication system in our angular app next we will explore how to protect your routes with guards and manage token expiration effect actively now let's quickly test this system that we have built so far so right now we don't have a nodejs or backend app to test with so instead of creating a new backend app I will just use a redim made online dummy backend that we will use to login to see if our logic works or not so I just quickly found this domain this website where it offers an API that you can use to test the login features so let's give it a quick try I did not use it before so let's see if that works so I'm going to copy this and paste it here okay now we have to I guess give this you can use any user credential from d.com users okay so here are a lot of users let's just use these this user okay right now we don't have any UI to login so what I will do is that I will simply in my app component I will inject my o service and call the login function through the Constructor okay inject and O service okay I have injected the Au service also make sure to import the inject function from the angular core now let's define a Constructor and in that I will access this. Au service. login and then we will pass it an object that will have username property and this is the username that I got from that website then I need to pass the password and let's copy the password from this website now let's add password Here and Now I will subscribe to [Music] it okay now let's quickly test it uh by the way this will give us the sample output so this is the response that that it will look like this it will have token and all other information so I will make few changes here here we are not getting token we are getting a payload that is response and here I will use response dot it will have the token property like this okay and here I will add type any for now and we know that we get only J token in this so in just instead of having token I will just add token here okay now let's quickly test it so open the app and let's reload it I don't see any request yet but I can see an error uh it is saying that HTTP client is not available the reason is that provide the HTTP client in normal angular apps uh where we used to have app modules you can simply add the import the client module but I'm using angular 17 and I'm using Standalone component so that's why I have to go to the app.config and here I need to provide the HTTP client in this way in this way it will be available thoroughly now let's test it you can see that as soon as it Reloaded The Constructor of the app component was executed and it called the login function and it worked it gave us a response from the network request and it has a token and the username okay so now the token should have stored in the local storage to check that open the application in the local storage area uh let's see we have it or not yet uh I don't see it yet so let's see where did it go so in the login we are calling this thing and we are also calling store token and we are also saving it let me add an alert here just to see what happened here okay actually let's alert the JWT and now you can see that we got the token okay actually the local storage was added but there was scroll that's why I could not see it now I can see it this says created with this key I can now remove the alert okay now we have the J jwd token now let's make another request to another end point I will now hit that API so I will try to get get the current Au user but in order to get that we need to pass the token so let's use this one and try I will call a function create a function in the O service get current o user and then I will return this do HTTP do get and pass this endpoint and by default it is already get method I will attach the uh headers to it and in the header I will pass this header okay authorization mirror and here let's concatenate the token we can get the token so let actually yeah I got the token now I can simply attach it here by using concatenation all right now I will simply return it okay now here instead of showing the same response in the logs I will call this. Au service. get current current Au user do subscribe so as soon as we log in we will further send a request to the back end and get the authenticated user so go to the network now you can see we have two request on page load first one is login once we are logged in it send request to the endpoint to get the details of current user you can see now we have a lot of information here okay so you can now create a property here user is equal to rning okay now here I will add pre code and here I will add user Jason okay uh so we have to assign this response to that user in this way now this Jason would be visible okay you can see that entire object is visible all right so this was quick demo how to utilize it so but one thing that I wanted to show you is that even if you don't add this right now let me show you in the network whenever a request go out it tries to it added this authorization so this one this is the one that we added but if you remove it then it should be automatically added so let's try it I'm going to remove it from here and now see if that works uh it did not add the token because we have to add the Interceptor manually now we need to connect the our Interceptor with the HTTP client so go back to the app config and in this parenthesis I will pass another function with interceptors and I will pass it an array and in this array you can pass all of the interceptors that you want to use okay now let's test it okay reload it is still not working uh let's go back to our HTTP Interceptor so I did one mistake here if you clone it then you should save it in a new variable cloned okay now I will use this cloned request okay now let's test it reload it this time you can see the there is no error and in the me end point I got the response and the header was attached automatically so that's the power of Interceptor we did not need to add it manually it added it automatically okay so in the login it added the authorization as well it was not needed it added it because uh it was there in our local storage but if it is not there in the first place then it will not add it so so let's say I will remove it and now let's reload it at that time uh there is no authentication token in the local storage that's why it did not add it it login it got the token it saved in the local storage and now as we have the token in the local storage so any feature request to the back end will include the token along with it let me quickly show you something so this is the token that we have so if you copy this piece of code this token go to the json. if you paste it here it will show you the exact payload that it contain so you can read it you can see what is inside of it so as you can see that anybody can uh decode it so you should not save any sensitive information in this payload so even if someone can see it still your backend is safe because they cannot alter or temper this payload for example if somebody creates uh an object by thems and Decode by themsel and send it to the server they still will not be able to get it verified because server use a specific salt token or signature to verify if it is tempered or not so don't worry about that anyways uh I want to show you more detailed examples and uh practical use cases so this API is very limited so I am thinking to use this one because this has more options so uh we will try to use this as well so let's try this one so I will login with the help of this API and see what happens okay let's go back to the art service and here for the login I will use this one instead of that and this time we will get the tokens because this object will have two tokens so we have access token and refresh token so here I can rename it to back back to tokens tokens. access token okay now we can get the users profile by using the same token so uh here I will replace it with the new URL and now let's test it so we have to use this login detail so go to the app.config [Music] okay let's save it and try it right now it did not work because it is saying that unauthorized it did not work because we did not follow the instruction we have to use the email property here instead of username so let's do that and let's rename it here as well email email email and email okay and also okay great now let's try it reload it in the network you can see that we have the login worked and profile is also working it is including the token that we got okay that's perfect now let's move forward with JWT authentication in place it's crucial to ensure that only authenticated users can access certain areas of your angular application this is where route guards come into play Let's create an O guard to protect our [Music] routes so first we need to generate our AR guard so for that let's run a command Ng generate guard o press enter it will generate o guard uh we have to select an option can activate so yes can activate is already selected so angle CL will ask which interfaces you would like to implement for the guard I have selected the can activate by typing it uh by selecting the space key if it is not selected uh now let's configure it so this is the can activate guard so in here I need to inject the O service is equal to inject I'm using the inject function make sure to import it in this way and pass it the O service now I will use it if this dot Au service dot by the way we did not use this property yet out of the our service the reason is that uh we did not use it yet but we will we can use it uh to show some real time changes in the UI so here I will add call a function is loged in we have to Define this function as well actually we don't need that this keyword here because we are using local variable to access the service so let's define the is logged in function here okay now I can add my logic to test so it can also hold the old value so I will just get get it and now here I will if it is not logged in then I will use this. router actually we have to inject the router Service as well so for that add router here and name it router service and now here I will use router service na. navigate go to the login and then I will return false if it is logged in already then we will return the true okay so in this guard we are injecting our o service to check if the user is logged in the can activate method or o guard function will return return true if user is authenticated allowing access to the route if not it redirects the user to the login page and Returns the fals preventing access to the route now that our o guard is ready let's apply it to protect specific routes in our angular application right now we don't have any uh routes uh so we have to generate some components maybe and also we have to add some routes so here I will add my first route and here I will add path empty component would be uh home component will protect the home component so to protect it I will add can activate array here a guard and we will create another route and that will take us to the login component so the path should be login okay we have to generate both these components so let's do that NG generate home generate C home NG generate C login okay so let's see all right both of these components have been generated you can see their folders now you can import these components in the app routes okay now in order to make uh the these routes work we have to go back to the app component. HTML and here I need to add router Outlet here okay so here we have applied the O guard to our home route so this means that accessing the home component requires authentication if the user is not logged in they will be redirected to the login page guards are powerful feature in angula for controlling access to routes based on any logic you define such as as user authentication status by using our all service together with Gods we have created a secure authenticated routing mechanism now uh it's time to test it but in order to test uh we may have to create some tags in our HTML so right now uh it is showing these users here okay I will remove all of this code so don't worry about that so in the login component let's add few fields in the HTML I will will add an heading login and I will add few [Music] Fields input type text placeholder email and NG model would be email as well we need to import the forms module so that we could use NG model here now we need to define the email property here by default it would be empty and then we need password okay and now I will add another input after that for the password okay now let's add a submit button here login and I will wrap everything inside a form tag and here I will add on submit or submit I will call the login function and pass my event okay now let's define this function here so I have called the function prevent default so that it don't redirect a page because by default when submit button is clicked form tries to take you to another page or if no path is specified in action then it reloads the page so now here I will uh first of all I need to inject the ser Serv Au service is equal to inject Au service okay now I can use it this. service. login and I will pass it uh use email and password okay and I will subscribe to it logged in successfully okay now I can remove that piece of code from there uh let me actually comment out all of this I will remove it shortly okay so let's remove this and this as well for now okay now let's pass the correct email and password to see if that works and uh by the way if user is logged in successfully then we should redirect that user to the Home Route okay so these are the routes we need to p move user to this route back okay so first of all we need to inject another service router is equal to inject router okay now I can use it to navigate it is it will route us to the main root path okay now let's give it a quick try paste the email chain me inspect the element just to monitor the errors if there are any uh I can see some errors it is saying that if NG model is used within a form tag either name attribute must be set or the form control must be defined as a stand alone okay no problem so we have to define the name here to fix that error name email and name password now error should be gone okay now add this change me open the network just to monitor okay it is saying that logged in successfully and it redirected me to the homepage okay now on the homepage I want to display the profile information of this user so for that let's move the code that we commented earlier so I will cut the cut all of this code and move it to the home.ts file and let's uncomment this and import the missing things all right and we don't need to log in again because now we are logged in successfully okay I will just get the current Au user and it will give me and I will then display it on the home.html so let me get this HTML code and put it here and make it un comment okay now let's try again add the email change me click on the login and it should take us to the homepage and here it it was able to show us the payload that you can see and let me double check the local storage here we have the token there is some problem I guess when I reload it it takes it takes us back to the login page so we have to look at our o guard so there might be some problem here so I'm checking if it is not logged in then it should take us back so I should not have used this okay so I will use a different approach this one I will check the token in the local storage if it is true then it will tell us and we don't need token because token is already being attached automatically by the Interceptor okay now go to the go to the home right now you can see if you reload it it will not take you back to the login page because everything is now working fine now last thing I need to add a log out button on the [Music] homepage okay now on click I will call the function log out so here I will Define a log out function and I will access the O service and call the log out function let's see if that works I clicked on that nothing happens so there might be some problem or maybe there is no problem but I did not redirect user so everything worked fine and here you can use the router [Music] service okay now let's redirect user to that login page if user clicks on that let me login once more and we'll check the log out function click on the login okay now we have the log out click on that and it took me back to the login page and this time there is no local storage available that we created earlier and that wraps up how how to protect your routes with guards next we will tackle handling token expiration to keep your apps authentication flow smooth and secure so a key aspect of working with jws is handling the token expiration jws are designed to expire for security reasons but this can interrupt the user experience if not handled gracefully so let's explore how to manage token expiration and Implement a strategy to refresh tokens automatically first we need to understand how to check if a token has expired the JWT payload contains an exp claim let me show you in the jwd website as well this one okay so this specifies the Tim stamp when the token expires we can decode this claim to check if the token is still valid for our angular application we will enhance our Au service to include a method for checking the token expiration so for that go to the a [Music] service and here I will Define a function is token expired okay and here I will save the token from the local storage and then I will check if token is not found then just return true and if token is found then I will check con the code it is equal to JWT decode token okay so this JWT decode would be imported from JWT decode Library we have to install it npm install JWT decode press enter it would be available with that okay now you will be able to import it like that okay now we have decoded jwd token I will save the expiration so here we uh we are converting it to the millisecond by multiplying it with th000 so it is saying that it is possibly null so here I will check if expiry not found then just written true okay and then I will create a variable const now is equal to date now dot get time oops actually I have to [Music] instantiate get time okay now I will return the expiration date less than now okay so this method retrieves the JWT from local storage decodes it to find the expiration time and Compares it to the current time to determine if token has expired now let's tackle refreshing tokens idly your backend will support a token will support a token refresh end point allowing clients to obtain a new token without re authenticating so we will add a method to our Au service to handle the token refresh this method should be called when we detect an expired token ideally before making a request that requires authentication now let's define a function refresh token and return this. HTTP dopost any and I will send request to this endpoint to refresh token and then I will use the the pipe function on it and then pass the T operator I'm missing the second parameter so I will just pass an empty object for now and in the pipe I will pass the T operator okay in tab I am calling the function store JWT token okay so in this method we are sending a request to a hypothetical API refresh we are sending request to our API refresh token end point passing upon receiving a new token we store it replacing the old one this ensures that our user remains authenticated without interruption it is important to handle the scenario where the refresh token request fails such as when uh when the refresh token is also expired in such cases redirecting the user to the login page to reauthenticate might be necessary in this case in such cases redirecting user to the log Lo in page to reauthenticate might be necessary so now let's quickly test it uh now let's login again with the same user okay now I will add another button that will call this function refresh token okay so on the so here I will call a create a function refresh token and I will use this. service. refresh token and now let's link the that function with another button refresh token and let's register The Click event and call that function now I will keep my network tab Network tab opened just to monitor what happens so click on the refresh tokon nothing happened yet so let's see what is the problem uh okay we did not subscribe to it I think that's why it did not work so add a subscribe to it and okay now let's test it okay now our request went but I got uh an error bad request why let's understand okay we have to pass the refresh token along with that so remember that we were getting the refresh token when we logged in so let's see if we are saving it or not so go to the application we are not saving the token okay so let's make some changes in our code to save the refresh token as well so in the Au service so whenever we set the item we should be receiving the string that string should have uh a stringified version of a Json object that will have the entire object with both kind of tokens in it so I'm sending both I will stringify it Json do stringify tokens okay now we have the login and here we are saving it and on the log out we are removing it and in the so here we are getting it so here we are trying to decode it but instead of doing that we have to pass it first so here I will add the name tokens and I will save the token in a separate variable from the access token property now I will decode it it should work okay and here I need to pass the refresh token so let's copy the name of property that we have to use okay and now I can pass the refresh token I will save the tokens here and now I will pass it now I need refresh token okay uh something is wrong I guess I need to add typen here for now okay now let's pass this refresh token to it you can just keep it in this way simple okay so we also need to double check on other places so here so it is saying that it is possibly undefined because we are returning the undefined so you can simply use a question mark here to get rid of that error okay now we have to double check in the Interceptor to make sure everything is still working so we are getting the token so we have to extract the access token from it so we have tokens in it we have to pass them now I will pass it and I will return that token okay so we have the token here we are passing it here that's perfect now let's look at the O guard to see if everything is needed to be changed I think everything is fine here okay now let's give it a quick try right now uh there are errors so I will click on log out and log in once more so copy it paste and and password okay now you can see that we have a object an object in the token we have two properties in that object one is refresh token and second one is access token now let's click on the refresh token and see if that works okay this time we got the success message 2011 status and in the response we got this in the payload we are passing the refresh token and here we are receiving the response and once it is uh received then fresh token we we just save it in the local story but here we are doing another mistake we are passing the access token we should stringify the response and pass it so that it could be stored all together in the local storage okay so one last time let's log in again and see if everything is still working fine okay login is working and profile is being loaded on the homepage and refresh token is also working reloaded is also working log out is also working now if you try to go to the homepage it will not let you to go there because of the AR guard so it will keep you to the login page until you login it and save your credential in the local storage and there you have it you now now how to handle GWT expiration in your angular application so whenever your token is expired you can just call that function that I called on the button click there are different approaches you can try you can add timer interval to see after that time expiry time is passed you can refresh it or you can use any other approach to refresh it so now you are able to handle jwd expiration in your angular application keeping your user seamlessly authenticated remember token security is Paramount so always ensure your refresh token strategy is a scure as your initial authentication flow thank you for following along in this tutorial we have covered everything from setting up JWT authentication in angular 17 securing routes with a cards to managing token expiration so apply these strategies to build more secure userfriendly applications and just like that we have reached to the end of our journey on integrating JWT authentication into angular 17 application so let's quickly recap what we have covered today we started by understanding the btics of JWT and its advantages such as straight lessness security and scalability then we moved on to setting up our angular 17 project installing necessary dependencies and creating an authentication Service to manage login and log out operations we didn't stop there we also explored how to securely store jwd tokens and use HTTP interceptors to attach these tokens to our request ensuring the authenticated communication with our backend protecting routes with o guards was our next Milestone providing a robust way to secure your applications routes and finally we tackled handling token expir expiration ensuring our users remain authenticated without interruption the strategies and codes shared today are designed to simplify authentication in your angro application making them more secure and user friendly I will also try to provide this code as the GitHub Link in the description below so you can find the source code from there now it's your turn take these Concepts apply them to your projects and see the difference they make so got questions or want to share your experience drop a comment below I would love to hear from you and if you found this tutorial helpful please consider subscribing for more angular and web development content your support helps us to create more tutorials like this one at I Tec our mission is to simplify web development making it accessible to everyone everyone from beginner to seasoned developers by subscribing you are not just joining a channel you are becoming part of a community dedicated to learning and growth don't forget to check out our other tutorials for more tips and tricks on angular and Beyond and if you are looking for more in-depth content our playlist on Advanced angular techniques is just a click away thank you for watching and happy coding until next time [Music]
Info
Channel: AyyazTech
Views: 2,418
Rating: undefined out of 5
Keywords: Angular, Angular 17, Angular frameworks, Angular libraries, Angular security, Angular tutorials, JSON Web Token, JWT, authentication, authorization, frontend frameworks, frontend security, secure communication, token, tokenbased authentication, tokenbased authorization, user authentication, user authorization, web applications, web development, web development tutorials, web security, json web token, use jwt, use jwt token, how to use jwt token, JSON Web token tutorial, angular
Id: Nh6l9uzU6dg
Channel Id: undefined
Length: 47min 27sec (2847 seconds)
Published: Thu Feb 01 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.