Implement JWT token in Angular 14| Interceptors in Angular | Guards in Angular | Part 7

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and all right so first of all um thank you everyone Logan um thank you that now we are 10K subscribers okay like first I'll start how things got started like why I came on YouTube like what was the motivation behind it okay so the thing is that I will be starting YouTube and continuing this for so long it's been uh one year or more than one year I guess I remember when I started my YouTube channel on September 30th I think I put my first video on YouTube and uh that too it was because of few of my students because I used to give some uh free training to to some college student and uh I remember they got a project regarding sir can you can you help us to make angular crud the angular 11 credit I remember the angular version 11 was there at that time so they asked for me like sir can you please help me with with our project so I was like let's go ahead and make it so yeah I was talking about that grid operation how it has been started for me with that so that video went viral because then I come to know like okay there are a lot of students because I wanted to reach a lot of persons so that's why I created the video because few of them wanted so can you record a video and then send it to us and the video was that much useful to them so they asked questions sir why not upload this on YouTube and uh because of those three four students I did that and I saw that video went viral like I got around 100K views on it then that that actually quite motivated me to to Let's why not continue this and I think there are people who really need this kind of content so I thought let's go ahead and and just create like create and just help them like I I love my community I love my angular community and I want to do good for it as well so that's why I have continued and if you see my content are mostly on angular and Dot net but I'm also a react trainer as well it's not like I just know Anglo and Dot net I also train react node.js Java so all of them are there in my bucket list but it's still like if you ask me yourself what is your favorite so I'll always stick with angular and net core because that's how I started my career but one thing I want to uh say here that always do not love framework like I know always try to love programming not framework because framework can come and go anytime okay if you want to love something then do love the programming because if your Basics are strong okay if you know about uh what is object oriented programming what are those classes objects what are functions then it is more or less same in every framework whether it is react it is vo.js it is angular.net the concepts are same okay if you want to work on something then work on your Basics I would say work on your Basics so that if you're basically strong then no one is going to touch you you can learn anything learn any framework that's not a problem that's why I always try to motivate person do not love framework if you want to love something then love programming like learn those Logics learn the implementations all that okay let me see I got one more comment by VP career opportunities in dot net core in India how to grow as a.net developer career opportunities I would say it's it's vast because for example if I have an I was starting my career right so for me also it was a challenging in the first because I I was a Java certified developer but I got an opportunity in in a.net project so when I started that I felt it is almost the same almost same only thing changed was some syntax some syntax index was there so I thought hey let's go ahead and try this dot net why not this.net and you're talking about the career growth in India it is it is there so dotnet is a product of Microsoft let me tell you that and if it is a product of Microsoft then let me tell you it is not here from two three years it is here since 2000 when dotnet was the latest framework was released so I think dotnet is here to stay and with DOT Net 7 so which is released currently like they had worked a lot on that so it is quite faster now so one thing I can say that and yes.net is here to stay in India VP yes and if you want to grow as a dotnet developer I would say if you are just a beginner then try to learn them and then try to implement those concept okay if you want to learn anything it's better to do a project and then learn okay uh not just theoretical things you read it somewhere and you feel like yes I know.net and I know she sharp it's it is not like that okay always always try to uh create a project and then learn like learn something for one hour and implement it for two hours I would say learn them one hour and just try to create a project just try to grind yourself and just see how how you can make that project how you can use those learning into your project okay so follow this kind of pattern that's how that's what I did actually in my career and that actually helped me a lot okay and if you ask me those then this is what the tip I can give create a project and learn and learn it all right okay then so let me just jump to why we are here for so first of all let's see what we have completed in the last session so in the last session we have created something called as JWT token okay and JW token I told you what is the importance of jwd token all right so let's go ahead and implement the token which was created in the back end and let's see how we can implement it in our ah angular okay let's go ahead and start this now okay so for now let's first see what is the problem now if I try to log in yes that's a good thing that we have a validation here that form validation but if I just try to put um a username let me first create a username so let me do that again SK username is user at the 8123 email is again user gmail.com and password this time I will play easy one one two three four five six okay but this will not allow you know right because we have those validations as well which we have added so I'll have to go with again this one better this time I'll copy this okay now let's click on sign up I can see user added let's go here and the username was user at the rate123 and password was admin at the rate one two three Okay now click on login so now can you see the login is success and I came on my dashboard page so this is my dashboard page okay so let me add something here so that uh this should not look blank let's go here in the components we have a dashboard the HTML let's put here let's put here H1 okay that's it okay let's go on the browser and check can I see that or not it's still compiling compile success now I can see Hello which means this works okay so to come to this page I need to do login first and then I can see this page but if I go back I go back I again come to login page and now from here if I try to again go to dashboard can you see I can access so this is not a good security to be very honest so this is not good so to make this thing good or maybe like to put here um a good guard so for to protect our routing if you see right we are changing the route I'm changing the route from here from login to dashboard and this guy is allowing me to go to the dashboard page and which is bad correct which means this is problem related to a routing okay which means what we need to do is so someone is trying to route to a page so we should stop them okay so there must be some security right so in your building like if you wherever you live you have a security guard or someone okay who checks hey if you are if you have access to it if you have a token or something with you then only you can go go to the rumor you can access everything but if you don't have that then it should not allow okay it should not allow which means it should stop you on the gate itself it should stop you on the login page itself okay so to implement that there is something called as auth guard in angular Earth guard okay and inside that we will be creating making use of a guard whose name is whose name is can activate okay so we are going to use something called a scan activity in angular to protect our routing to protect our so that we should not directly go from here to the dashboard we need to protect it so how do we gonna do that okay so if you still remember that uh we have created this endpoint where we are getting the token whenever we are trying to authenticate we are getting a token okay let me show you that token again so let me show how the token looks like if I go in the network tab and again if I try to login again with the same user and here I put admin at the rate one two three and if I press on login let me remove the breakpoints and if you go on the network tab okay so can you see one thing here I am getting this in the preview I can get a token I'm getting a token from the back end and if you have seen my last video so you know how we have created this token all right so now we are going to use this token to protect our routing okay we are going to protect our routing now okay so let's try to do that let's go here and do that so in the angular in the angular we have to create a guard okay so I'm going to create it outside so in the app let me put up my charger okay now it's up okay now let's go in the app and create a folder called as guards okay and inside this folder we need to create a auth guard so how do we create so let's right click on here and click open in term integrated terminal so this will open here so you can see it is under the guards folder and now let's hit a command NG G4 generate G for guard and the guard name is auth so we are creating a auth card so once you give the name auth let's see how the naming convention comes that's weird so it is asking for which guard you want to implement okay so we have total five guards in angular so out of which if you ask me sir which one is very famous and widely used I would say the can activate and can activate child people use can load as well but I'll talk about it later in my sum of my video I'll talk about each and every cards in detail okay but first let's concentrate on the very important one which is the can activate let's click enter and you can see a guard is created and that's how the angular follows naming convention name what you have given dot guard dot TS okay so this is our odd guard our guard Creator a can activate guard okay so let me remove all this so that should not confuse you by showing all these things but let me tell you about the most important part of this can activate guard okay a guard is nothing but a guard is nothing but this guard actually helps you helps you to return a true or false value okay this guard only helps you to return true or false value that's it that's the job of this guard people I'm not sure why people find it difficult Shashi I'm not able to understand guards how to implement them how to use them I see people struggling with the guards also in interview they sometimes fail to answer it but for me if you ask me what is God it's it's very simple God is just a kind of a method which helps you which gives a true or false value that's it and that too based on some condition based on some condition it returns either true or false that's it if the value is true then allow him to go allow him to use your project allow him to use your website if the value is false then stop him right away stop him on that page itself do not allow him to go to the next page or the dashboard page okay something like that okay all right so we have created the garden we know that this should return either true or false so we can make here as we can say return type as well as Boolean it returns a Boolean okay like that all right so what is that condition let's let's try to get that how we will create a condition so one thing we can check right so whenever we are logging whenever we are logging in the application okay we along in the application we see we are getting a token okay if we are getting a token which means user is logged in if you don't have token which means user is not logged in so do not allow do not allow the routing correct so we have to implement that so to implement it so what I will do is I will create a service so I already have our service so inside this I will be creating a logic logic to check if I have a token or not I have a token or not if I have a token I will be storing that token in local storage okay so that's what I'm going to do next so to do that let's go ahead and let's go ahead and go in your service and try to create that service it's simple all you need to do is let's create some methods few methods I will be creating first one to store token okay so just storing a token again it's just simple we will be showing it in local storage Dot Dot set item okay how do we set it we just give here as what is the key value how we want to show I want to store it as a token and you need to set a value right you need to set a value so I'll say a token value okay and this token value will be passed in this methods parameter so store sorry it's token value okay okay token value okay and now I can just it's over type string uh token is a type string it's not any object or something like that okay it's just a string so this is my token all right now now this method is ready now there should be one method which tells that um get token so let's create a method called as get token this method will be useful later I'll tell you how Okay so this will return local storage dot get item I want to get the token okay so this is setting the token this is getting the token whenever we require so we are doing this in a service right and service is helpful whenever we need to call something uh this is a Singleton service so this can be called anytime any point of time okay so set and get is done okay now if I want to check if my user is logged in or not how do we get that so let's create one more method is logged in this guy should return a Boolean okay so let's try to return so we can say return local storage dot get item okay but this is a string this returns a string right so if I hover on this it says type string is not assignable to a type Boolean which means this is returning a string but we want a return type as a Boolean so we can just add here to exclamation and now this converts your string to a Boolean value which means if there is a token then it will return true if there is no token if the value is null then it will return false okay so that's how we created this method is logged in okay so we have three methods now store get and is logged in now what we will do we are going to use this method first okay whenever our login is success so let's go in the login component and let's go here on the success call so if you see right so this is our success call so whenever my login is Success what I want to do is I want to store the token okay so for storing it let's call the service so I have injected the service already auth and in the earth we have the method called as this dot auth dot store token store token and it accepts a value okay token value so we are getting if you remember right in the response in the response we are getting the token okay in the response we were getting the login response dot token if I again try to login user at the grid123 and password is admin at the rate one two three if I again log in here can you see I see just forget about this user and I'll talk about this later but this concept on this this guy authenticate method so this returns a token so this is the object which is returns okay so here we have response Dot message so for a token we have response dot token so these are objects that's what we are using so for storing you can say response Dot token that's it so this guy will now store your token okay this guy will store your token [Music] all right now let's go ahead and check check in the auth guard check in the auth guard now I told you right if the token is there then return true which means the user can log in if the token is not there we can return false correct now let's go here in your guards and now here try to call that service or service so for calling the service we need a Constructor because Constructor in angular is used to inject services okay let's call the service auth or service and it is imported on the top as well you need to import this and now we can use it now let me remove this true value and now I can say if this Dot auth dot is logged in so this is logged in returns are to Boolean value right if the user is logged in if the user is logged in then you can say return true okay and if the user is not logged in if the user is not logged in then you can say or let's let's try to have a else block okay we'll try to optimize it later you can say return false that's it this is what odd guard is don't you think this is how do you think is it easy or difficult what it's very easy right just need to check if he is logged in if he has written true no then return false that's it let's save all the changes and now if you tell me like is it ready now can can we restrict the user to not to log into our application like to access the dashboard without login the answer is no why no because this is only 50 implementation the important implementation like important thing is to make it use we have just configured something now we make you now we need to make use of this Earth guard okay the configuration is done now the next part is usage how do we use so this is belongs to routing right so for that we will be going in our app.routing DOT module okay and I want to restrict the dashboard correct I want to stop the person if you don't have access you should not go to dashboard so for that I need to use scan activate so this can activate will help me and inside that we just need to pass our guard what we have created the guard name is auth card click here this will be Auto imported on the top okay auth guard so now it is ready now it is ready to use now this dashboard will be restricted no one can use dashboard if you are not logged in let's go on the browser and check let's do a demonstration then let's go to the login page and let me remove if there is any token present all right let me reload the page again yeah now I'm trying to I'm trying to access my page if I try to go to dashboard it it throws me to a blank page which means it is not allowing me to go to the go to that page okay but this is a blank page see I'm not able to access the dashboard okay again if I try to go on dashboard I'm trying again bro I'm trying again let me copy this so that I can try two three times no cannot access let me try again no but I don't want to come to this page as well right and there is nothing showing here like okay if there is wrong what is going wrong because I cannot see anything so let's try to make all this functional now okay now let's again go in your uh auth guard and let's try to add few more things if the login if the user is logged in okay so I want to send him to the dashboard page I want to send him to the dashboard page we are not saying that here so we need to say that like hey if if you have access then you can go to the dashboard page okay so let me just try to implement that as well if you have no access then you cannot go to the dashboard place let me say private again we need to play with the route right route router and we need to call the router so this router will help me to stop the user on the login page because if you see right it is go it is going on a blank page which I don't want okay I want to stop him to the login page okay let me go in the routing and let me check if the path is this okay that's correct all right now what I will do is I'll say here if you are not logged in then I'll say this dot router Dot navigate to the same page to the login page we can just tell him hey if you don't have access so you should stay on the same page okay you should not go to any other page something like that we can do okay so this has to be like this it's an array stay on the login page if you don't have access but if you have access then it's true you can use the application something like that and also we will try to give some errors as well so that we can check what is going wrong so for that again let's try to create our toaster use our toaster it is NG toast service and here we can just say this dot toast dot error inside that we can add details detail will be it's an error and we can say summary summary will be um please login First okay something like this now let's save it and now let's go on the browser to check again what is the behavior if I again remove this and if I try to go to dashboard can you see now it is still on the same page and we can say please log in first okay again let me try if I again try to go on dashboard see it is not allowing me okay so that's how you implement your art guard that's how you protect your route so now no one can access your dashboard page but what if I put some your my username and password and the password was admin address 123. wow now I can access my dashboard page okay but there is one more catch one more catch there should be some button like logout button or something like that by which we can sign out right if you have logged in so there must be some sign out button so that we can remove the token after sign out okay okay let's try to implement that let's go in the dashboard and let's add a button very quickly I think we have bootstrap already added in the project so we can use button dot BTN Dot bdn danger for a red color and we can see your log out save it and let's see so we have a login button ready now what we need to do is we go here and we create a logic for log out so for logout what we will do we will again create a service okay we'll create a service for logout so that's the correct way of doing it let's not do it directly from here so let's go in the service and create a sign out method sign out and here we can say if someone clicks on sign out I want to clear the local storage so local storage dot clear okay you can clear a single item as well by saying local storage dot remove if you want to remove the token you can do this as well okay but I always follow this one like let's clear the storage if you're not using it anything so we can remove it all the local storage space has been saved so now we are removing the token from this line and we can say here that okay if this is done then you can route to the page we can just add your routing as well here if you want so you can do that as well you can see private router okay then again call the router because we want to go to the login page now again so we can say this dot rotor dot navigate and we can come on the login page again okay so this method is done and now we will implement this now we will use this uh sign naught in your login oh sorry the dashboard where we have created this method called as logout so let's again import sorry the inject the auth service here okay and now here let's take this dot auth dot sign out I'll take some questions guys after this once I completed this because we need to uh talk about Interceptor as well so I'll do that after this okay so for before that we'll take a five minutes of q a if you have any questions regarding whatever I have explained okay so this is what logout is and we need to call this method on click of this button so let's do that you can say log out I hope the spelling is correct yeah the spelling is not correct so it throws an error so that's fine again Make It smash log out okay now this is ready now let's go here click on logout become a login page let's try to access the dashboard again click we cannot log in please log in first and now we need to log in again and we can log in your application okay so that's how we have implemented auth guard in our application so if you have any doubt you can let me know in the chat interceptor again one of the very important interview question people ask what is Interceptor in angular how do we use it so we are going to make use of Interceptor so that you can answer the same thing in your interview as well okay that's a very important concept of angular interceptors all right so now let's go ahead and check the second problem not the problem but yeah what we have implemented let's see here in your dotnet application so I need to open up my.net application now let's see let's go ahead and see uh how why the Interceptor is needed first of all why the Interceptor is needed okay so guys I have created a new endpoint if you see right uh I think people will have till you if you have followed all my videos so you will have till here till token create token so I have created one token here sorry uh API here and the API name is get all users okay get all users let me remove this authorize for now let me remove this authorized for now okay so it's a very simple method okay I think I I have not taught it in my previous videos but you can see here I have a very small method and this method returns a list of user who has registered in your application okay so let's go here and let me just show you this is the API how it looks like if I click get try it out execute okay so what I want to see is see can you see I'm getting an error okay because I need to restart the application because I remove the authorize I need to restart the application let's wait for it to get restarted okay okay here it comes so we have this API created uh get users if I click on try it out click on execute can you see I am getting a list of users from the database I'm getting winter of John random see I have added the random and the last one what we added is SK and with the username as user at the one two three so the thing is I have created an endpoint and I want to protect this endpoint I told you right token helps you to protect your uh your services your your data your resources so this is my resource which is stored on my database the list of users I want to protect this list of users okay if you see like anyone who will if I deploy my application and anyone who goes to to this routing like my www dot my application slash API slash user so they can access my list of users without even login without being an authentic user they can log in my application they can access my data so that is bad right so this is not good so we can protect it in.net core okay because half thing we have already did we have created a token already okay so here on this line we have created the token and now we need to make use of the token to to create the security level okay and if you go in the program.cs file I mentioned one thing very clearly that make use of this app.use authentication and app.use authorization this is the pipeline where we have registered our authentication authorization so this is the guy if you need to add so that you can use authentication in your project so that your token will work actually okay let's go in the user controller and make use of a attribute called as authorize okay so we can make use of this authorize okay to protect your your API so now my this API will be protected okay if you don't have token then you cannot access my application for example let me restart this we start the application because I made the changes and let's go and try to access this API again okay let's try to access this API if I again click on get user try it out click on execute whoa I can see an error I hope you guys can see let me zoom in in a bit yeah can you see the error it is four zero one error 401 response status is four zero one which means you cannot able to access my my API which means you are unauthorized four zero one means you are unauthorized if you have a status code 401 let me show you status code 401 okay this indicates that the client request has not been completed because it lacks validate value valid authentication credential which means this guy is not authenticated so you cannot access my application you cannot access my API that's what he's trying to say by returning 401. okay so now how will I be able to access I can only use this if I have a token with me if the user is genuine if the user is there in my database then only he can access the token for example if I have a postman maybe I can show you okay I don't have it yet so let me just try to uh create one uh this endpoint let me try to use it in your angular application so let me just show how I have added this okay so let's go in the app go in the service and in the API service I have created a method API method a very easy one a very simple one okay again I created a API service uh now you guys know how to create API right API service apis so right click here open an integrated terminal and just write the command NG G4 generate s for service and the service name is API and this should be in this folder Services folder okay and this will get created once we have this so we need to make use of HTTP client to do the API calling you guys know all this I guess because I have explained about how do we do login and sign up it is almost same but this time we are creating a get user call get API call and this is the base URL which we are hitting if I show the same here yep yep yep then this is same and you see I am hitting this URL the request URL is this and you're getting four zero one okay let's go and now this service is ready and now I want to see all the list of user on my dashboard okay I want to see them on the dashboard so let's go here in the dashboard and let's call this service API service okay inject the API service and from that I am calling this guy so I created a property called as users list of users array and I'm storing all the response what I'm getting from the API inside this users okay and this users I want to display here so to display them let's use NG for okay let's say your star Ng for let user of users and I want to display all the username so I can say user dot username okay let's save this let me check the yeah that's correct okay now I want to display all the username okay if I save it and now let me see if the con yeah it's compiled successful that could mean go here first of all let me try to again do the same thing just to test if everything yeah it works let me try to access now if I say admin at the rate sorry user at the rate123 the password will be admin at the rate123 and I hit enter now okay I can see the dashboard page I can see the dashboard but I cannot see the list of users I cannot see the list of user let me see what is the problem inspect and just see the error wow as I have told you we are getting an error called as four zero one but you'll ask me why but we have successfully logged in right and you told me that okay if you log in with your credentials then you can access all the API all the resources but still I'm not able to log in why the reason is if you want to if you want to access that URL you need to send that token to the back end okay you need to send the token to the back end how do we send the token to the backend okay what is the way what is the various way to send the token to backend the thing is we make use of interceptor if you make use of interceptors okay how do we send the token with interceptors okay for example we can send token by using the headers by using the headers okay now you look especially what is header now I know this question can come to this question comes to every fresher and beginners who have just started so what is header in in your in your web application in your web what is HTTP headers and all these things so let me just try to show you what is headers if I again try to access the same URL same endpoint for login okay if I click on login if you go in the network tab can you see I'm getting this slash user as an f401 if I open this if I go in the headers right here is the problem so he is asking me to add the authentication Bearer token is asking me to append the token if you see this token right he's asking us to append this token append this token on the header so that backend can validate okay so my job as a front-end developer would be I want to append the token because my backend developer made he added the security that no one can access my resource my API if you don't have token so where we will send the token from how do we send the token who is the transmitter the transmitter is the mediator guy is who is taking your token is your header header takes your token and give it to your backend okay now we have to append the token to append it on header who in angular helps you to append those or modify those headers we have to modify the header right we need to add one extra header called as authentication we want to set a header to setting the header or to modifying the header there is something called as interceptor Interceptor this Interceptor helps you to modify your request and response URL we can modify them we can change them based on our requirement okay so whenever suppose the a request comes right so here we have our Interceptor so this Interceptor will take it he will modify it and he will send it okay request and same thing in the response when it is coming here is the Interceptor he can modify it and he can send it to the back end so he is the middle guy who helps you to modify your headers modifier headers whenever you are doing HTTP call so let's go ahead and see it in practical how do we create an Interceptor in angular so let's see that first so for that let me again create a folder so there can be I have seen a lot of Interceptor located so that's why I create a folder and then I create the Interceptor inside that interceptors and inside this I need to create my first Interceptor so again right click here open in integrated terminal so we are inside this folder now you can say NG G for Generate Interceptor and I want to give the name of Interceptor as token Interceptor because we are doing it for token right we are setting the token on the header value if you have any doubt please mention it in the comment section so that I can see and I can answer them that will be helpful for others as well okay if you have questions do ask me in the comment okay so that's how we create a token uh Interceptor NG G for Generate Interceptor and the Interceptor name I want to give a name of Interceptor as token if I hit enter now I will show you how the naming convention angular schematics follow so it gives your token name Dot interceptor.ts if I open this wow so we are getting a boilerplate code okay so this is the beauty of angular actually we don't need to write it helps us in productivity it helps you to generate this boilerplate code thanks to angular CLI so people can ask you what is angular CLI how is it help you you can tell them it helps us in the productivity it helps you to generate the boilerplate codes for us so that's how a boilerplate course look like an Interceptor we don't need to write them on from scratch right it saved a lot of our time two three minutes it have saved of mine so that's the benefit of CLI as well angular CLI okay so this is how our Interceptor looks like okay and now we want to modify we want to modify this interceptor okay so what we need to do we need to append that token on the header okay so where we have token the token is in local storage okay how to get the token I have created a method right I have created a method called as method called as get token this method we will be calling so let's go here and try to call the method so we'll say private auth service okay it is imported on the top now here we need to call my token so my const my token equals I'll say this dot auth dot get token so inside this I will get my token okay I will get my token inside this and now from this token I want to modify it I want to modify this token in such a way that it gets appended on the header okay if I just show you the header right now how it looks so there is nothing called as authentication or anything here in the header right can't you see anything no you can't see anything called as authentication or you can't say never token is appended okay let's go so now we will take this token okay now we're going to modify this right so for modifying it we will just say here that okay if you have the token then modify so I'll have a if condition if I have my token if I have my token then I want to modify I want to modify what I want to modify I want to set I want to set the set the token value okay set the token value now Shashi use modify and set modify what will be modified your request will be modified so we can say here your request equals so request Dot clone we are creating a clone of the request and inside that there is something called as set headers modify and set modify the request and set the header I want to set the header it's very easy how do we set it we can just say here authorization it's an authorization we want to set the authorization and we can just say here she is cool okay so I have a token here and I'm trying to set it like Shashi school for now so once I have set the header right set the header right I can just say here now in the next line I can say request request dot handle why is it not coming I'm not sure request sorry it should be next because we have a next on the top this guy we need to use is the Handler so let me remove for now oh it is already there I'm so sorry guys it is already there so in the next line we are handling so that uh if you guys know about uh I think most of the experience person will know uh this next we'll call your the pipeline in in.net core people say like next next it it sends you to the next pipeline which runs so that's how it is actually so whenever we say next dot handle now our request will get handled so that's how we send the request again what we did we had the request first we modified it based on our requirement and then we are sending it back go back now let me just save it still if you say now we can send the token right the answer is no why no because still we need to configure them okay we need to configure them sorry we need to use them configuration is done now we need to use them how where do we use it we will use it in app module and in the provider in the provider we need to provide we need to provide them okay so let's go ahead in the providers array and let's say provide what you want to provide what what you want to I want to provide HTTP http interceptor see it is imported on the top I want to provide http interceptors and the next I'll say okay which class should I use which class should I use if you know right this is a class the Interceptor is a is a class right it's a class so which class should I use I will say Okay use the token Interceptor class and I'll say here multi S2 because it can have you can provide many right inside so multi equals to true now is now will it modify my request the answer is yes now this guy will modify your request okay let me show you how let's go on the UI let me click on logout and let me remove everything and now let me log in again I'll say user at the rate one two three and admin answer it one two three if I click on login okay the login is success now if you go here okay can you see something can you see something here there is a authorization header has been set and what is the value of that set a header is cool that's what we added right that's what we added but we don't need to set any random value we need to set the token because that's how this is going to travel in the request header can you see I have modified the request header he will travel to the back end so what we want to send we want to send my token how do we send it we need to send it via a bearer we need to write their prefix not a prefix but the first term is beer this is a BL token be error and then we need to just say here my token my token okay this is how we do string interpolation in es6 okay if you have doubt so let me give you the what does it means it means something like this it means the error space and then your my token something like this string concatenation okay that's how you do all right now now in this way our token is set now we are sending the sending it to the back end okay now let's see what happens let's see what happens again let me just go in the node and I need to log out first click on logout and now let me see your user add the rate123 and password will be admin android123 click on login wow can you see now I am able to access now can you see my user can you see my user now it is 200 200 means success response now we are getting 200 not 401 which means now this guy can access my token now this guy can access my token okay for how long he can access so there is a timeline what we have set in the dot net we have added expiry time as one day which means my token will be valid for one day okay let me just show you the good fact about it let me just try to remove this and just say here dot add seconds 10 seconds okay let me save it and let me restart the application again okay I added it for 10 seconds and for doing that there is one more thing it is required if I remember correctly and that is we need to send skew time like for example let's go in the program.cs okay so here we have configured it right so there is something called as time expiry in the program.cs file you can see let me just go there navigate and let me add that line here okay so in the token validation parameter there is something called as clock skew here we need to say that okay time span dot zero so that it should match so because what happens right if you put here as put here as 10 seconds but still it will not take 10 seconds it will take five minutes so the minimum time it is valid is five minutes uh five minutes yes but if you want to match it exactly your time then you need to add this guy in the program.cs clocks Q equal to time span.0 now what will happen right so now this will only take now your token will be only authentic for 10 seconds okay once the token is expired you need to log in again that's the problem okay let's restart it now and let's see the behavior if it is correct or not okay so I came here and now I go here and run my application locals okay now I'll try to access a user android123 and password is okay now I will be logging let me inspect element so that I can see the errors and everything okay I click on login okay let's go in the network tab yeah the login is success and I get 200 for this now let's count for 10 seconds or let's wait for 10 seconds okay so this 200 200 200 Let me refresh it can you see after 10 seconds it's it's expired the token is no more authentic it was only for 10 seconds that you can see your data okay so that's why I have put there as one day that at least for one day your token will be valid so that's why most of the companies prefer the token expiry for 1R and after one hour if a user again tries to log in right they get Auto log out or something like that auto logout happens and they again they need to log in to fetch the data okay let me show you that again if I again login right again login if I say user at the rate one two three and I say uh admin at the rate one two three if I hit enter now I can again see the data now if you again uh count for 10 seconds this will get expired this will get expired I can see the data can it expired after 10 seconds it is expired and again we can see four zero one which means unauthorized you need to log in again to see your data okay so that's how I have kept that thing there so let me again make it as add this as one day so my token is valid for one day okay in future there is something called as a refresh token so let me also say that as well there is something called as the refresh token uh which I will be covering refresh token very important topic and it's an advanced topic it is not mostly ask for a one year or two year experience person I have seen it they expect this from at least two three years of experience guy how do we Implement refresh token in.net core okay so I know a very best way to do it which I will be sharing with you guys as well so just wait for that video where we will Implement refresh token in angular and net core okay so just wait for that we will Implement that that's for the third thing is we can handle errors as well we can do error handling as well okay let me just show you that how we can do that error handling so here in the request.next.handle Dot okay so this actually returns something very interesting let me show you that as well so this is an observable right this is an observable so what we can do here is we can pipe we can make use of pipe to catch the error so dot pipe so inside that we can cache the error so there is something called as catch catch error here d c h e r r okay it's it is coming from RX yes okay it is all are coming from rxjs so we can catch error okay and there is a selector right there is a selector where we need to catch it we can say error okay this has to be like this and now we can say if if error if your error is an instance is instance I guess e r r instance of Errors http error response if this guy is instance of HTTP error response okay then what we can do is we can get the error codes we can get the error codes from this guy okay how do we get the error codes it's again simple if error dot can you see error dot error status if the status is equal to equal to four zero one so we can handle it here we can just put here as this dot we can use the toaster we can use a toaster so let's use the toaster private toast NG toast not the module Sushi it is NG toast service okay and here we just say uh this dot this dot toast dot I can give a warning or error whatever you would like to give I can just say your sorry this has to be detail I give here as warning and I can give the summary as token is X expired login again okay and also we can navigate them to the login page private router okay and we can just say here this message and then we say this dot Rooter dot navigate and go back to login you don't have access anymore that's how we say all right and now let me see why is this error is coming it says error of is not assignable to parameter of any God observables so why we will fix it no worries so let's go here this is my if block okay and in that we can say return through error this will handle other than that if there is any other error so we can say throat W through error again coming from rxjs and this guy has to be sent a new error which we can handle any other error we can just say your new error and inside that we can pass some other error occurred that's how we written okay that's why he was complaining here you haven't you used this guy okay so that's how we return the throw error in the catch we need to throw this error right if the error is of type 401 which means my token is expired then we can say hey token is expired and please log in again okay but if there is any other error so that can be handled by this guy by this written through is it clear everyone let me see in the comments if you have anything no no questions I hope this is clear if yes please thumbs up in the chat if it is clear because I will show you the um the Practical thing now on the UI how this works how this catch the error and handles handle the error if you got it please say yes in the chat okay okay clear okay good all right then let's see it in the practical if I go here now if I go here now again I need to change it to uh one day sorry 10 seconds add seconds yes yes okay save it and let's run it now this for 10 seconds again my token will expire in 10 seconds Swagger is running let me open the look angular as well and now let's see if I say user add the rate one two three and the password is admin at the right one two three now I click on login the first request takes always time in dot net but yeah I can see login success now let's wait for 10 seconds yes it is accessible accessible accessible whoa it has logged out and again see token is expired please log in again okay so that's how it works that's how your interceptors actually help you to do error handling as well if there is any error he can cache that error and he can return if you remember right uh that warning will only show if the error type was four zero one which means this is we are getting here a status code as four zero one it is matching this and then it comes in this Loop and then this guy is triggered it is warning and it is throwing us to the login page again okay so that's how we handle errors in angular so by Interceptor we can do this as well okay so now you know right I think Rahul was asking me about Interceptor so I hope this is clear to you Rahul if yes please do if anybody have still any issue with the intercept do let me know any questions related to interceptors do let me know in the chat okay um all right now so this was about your token thing in angular how do we make use of JWT token okay how do we make use of interceptors how do we make use of guards in angular okay and I think that's that's pretty much it for today in this in this session actually where I have explained you about uh using JWT token in angular in the next part what I'm planning is that I will be taking up the dashboard page so we will be creating now we will be focusing something on UI side so we will try to see how do we create a good dashboard in angular okay so that I'll take in the next session where we will be creating a beautiful one okay not the ordinary just a small table and display the user record no I'll create a good one uh because what I'm planning is for example so I got a lot of questions that hey Shashi how do we how do we display the username on the nav bar correct how do we show them based on role if you remember right okay let me show this again I think this will be quite good to to make you guys more interested about the next session why this is important uh if I just show you okay so let me just show you the username the username is okay sorry let me log in it again okay if I click on login let me remove this if you guys remembered one thing that we are storing something we are storing something in the token if you guys remember if I just copy this let's go in the website gwt.io control V can you see here that I am storing something called as roll and name in the token so I'm showing these two person in the token and I want to access them in my us because there are requirements which comes to the user that hey I want to display the name of user here like for example if I just go on the bootstrap not the grid just the bootstrap and I want to get the nav bar let me try to add it quick thing I can do this one or or why I can do I'm searching for a good one just let me copy this guy and let's go here and I'll take all the questions I see questions are coming I'll take all the questions uh after this okay just just wait for it I'll take all these questions no worries I will be here okay now let's go here in the HTML and let me remove this hello dashboard to control V and let me remove the inline forms as well you put a div with saying pan hello Ctrl save now let's go here and let's see how it looks okay the token is expired again okay okay again so sorry I need to change it to add but can you guys see my token got expired automatically and I came to I have been thrown to the login login page okay let me run the application again okay let me run the local host photo double zero angular and let me okay again first request takes time so now we have a nav bar and here we have hello Shashi written so what I need to display these guys okay I need to display this I'm going to display this whenever the user logs in suppose uh some other users logged into my application and I want to show his name so how can I do that how can I do that dynamically so that thing we will cover in the next part okay how to add your name dynamically how to retrieve some data from your token and display it okay so that will be done in the next session okay that's how we I will be targeting but with a better UI I promise a better UI not like this okay it's okay yep all right guys so that's it from the today's video uh we have learned a lot today and again if you have any questions anything for me you can just comment on my any of my video you can just DM me on insta or you can also connect with me on telegram so we have a lot of medium where we can communicate okay so you can just connect with me there all right hello bye bye and keep learning guys everyone
Info
Channel: Let's Program
Views: 32,001
Rating: undefined out of 5
Keywords:
Id: qugH2AbakEE
Channel Id: undefined
Length: 67min 10sec (4030 seconds)
Published: Tue Nov 15 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.