🔑 JWT Authorization | Angular Router Guards | Token Refresh

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I’ve seen JWT advertised as a solution for stateless servers/services. But when you keep a list of JWTs for invalidation (so the user could logout) it’s no longer stateless. If your server is composed from micro-services or your server is behind a load balancer, you’d probably put your list of valid JWTs in a redis store - so now you need a database with JWTs.

There are benefits of course, especially when your server is composed of stateless services, but I don’t see why you’d need to use JWTs on the frontend side.

I would recommend having an api gateway service which uses cookies when communicating with the frontend, but when the session is valid, would use JWTs when communicating with the backend services.

Something like this (from google image search): https://cdn-images-1.medium.com/max/1200/1*gVkz7gEGrXwD7nxeT1o0nA.png

👍︎︎ 2 👤︎︎ u/TanelTM 📅︎︎ Dec 15 2018 🗫︎ replies
👍︎︎ 1 👤︎︎ u/bpietrucha 📅︎︎ Dec 18 2018 🗫︎ replies
Captions
in this video I will show you how to implement angular application authorization based on JSON web token abbreviated as JWT you will learn how to restrict access to the given parts of your application with router guards so the only authorized users would be able to access them also you will see how to intercept HTTP calls an access token required by server finally you will learn why we need to refresh token and how to use it transparently for the user so that he is unaware of access token expiry and following a refreshing process this is angular academy if you are new here don't forget to join slack channel to discuss the topic of this video using the link in the description also if you want to be on top of future lessons click subscribe our application for this tutorial is composed of two routes first route is available under login URL as you can see right now this is our login component the second route is available after login under secret random-number URL and the component under this route presents a random number generated by the server if I manually try to run access protected URL I will be redirected back to login page so let's try to log in and analyze the application further we managed to login to the application and couple of things happened first of all note that we can access previously unavailable route secondly we can see some API calls let's take a look at them we can see that the request to a random API endpoint has authorization header with some string this is our JWT token it was generated by the server when we were logging in we the credentials and you can see the result of that query here JWT and refresh token later I will show you my back-end server implementation in node.js with X present Passport for now let's focus on angular part finally let's take a look at local storage for this website the application stored both tokens and they are going to be used when we refresh the page so let's try to do this as you see I totally refresh the page and those values because they were persisted in the local storage were used again providing our access to protected route again now let's take a look how we can implement such application our route components template app component HTML contains router outlet so it will present routed component here app routing module is the place where the route routing configuration is implemented we can see two routes here the first is previously mentioned login route with login component additionally we can see it has elf guard defined inside can activate all right this is the router guard that tells the angular router if it's allowed to activate given route let's take a look at that card this type of guard implements can activate interface forcing it to implement can activate method in our case we make use of our service that answers the question if the user is locked in if that's true we would like to redirect the user to our secret page as there is no need to login finally we need to give an answer to the router if the route can be activated again in our case we would like to say yes only if the user is not locked in this is the moment to take a closer look at our service our service has a bunch of important methods implemented let's analyze them one by one first we have login method this is HTTP POST call to a back-end API with user credentials since we receive a observable we would like to use pipe again to apply some RGS operators first is tap which would actually take the values from the stream and apply some side effects in our case it's do login the user method later once we consider it successful we would like to map the value to true and in case of error we would like to display alert to the user and return observable of false because we would need to somehow provide the result of this method to a code would which would be calling this login method and inform about either success or failure of this operation so what does do login method login user method do do login user would take the username and tokens and just store the user name and call store tokens store tokens method we take our tokens and save them to local storage under defined keys so this is how we do login let's see how we can implement logout method the same as previously we are doing HTTP POST call two different this time API endpoint logout inside of the body would like to pass over refresh token so that the server would know which refresh token to remove and then it would not work anymore then we are using pipe again to use tap operator to execute do logout user and again map the result of this whole method to true so that the client of this method would know that the operation succeeded and in case of error we would like to display an alert and map the value to observable of false what does do logout a user do do logout user would removed log at user name from the component and execute remove tokens as you may presume remove tokens would remove access tokens from the local storage so for now we have learned how to login and logout but our service has also won a very important method refresh token I will explain the concept of refreshing later in this video but for now just note that it executes HTTP POST to refresh api endpoint with refresh token in request body and expects tokens object to store JSON web token in local storage so we have our tokens stored in local storage and we want to authorize outgoing HTTP calls with JWT token of course we can manually add authorization header to outgoing HTTP calls in service methods but this would cause a lot of duplication instead we can make use of HTTP interceptor here you can see token interceptor which is angular provider that implements HTTP interceptor and intercept if we properly register this provider what I will show in a second this method would be used to intercept or in other words process every outgoing request executed by HTTP client what we want to do here is to check if h WT token is available and attach this token to outgoing request so that it will be authorized let's examine our token method what this method does is takes request and set authorization header with the value beaver token so exactly what we saw at the beginning of this video next part of intercept method takes care of error handling and refreshing in case of 104 o1 HTTP error which is unauthorized error code but before we do this and analyze this part let's look how to properly register our token interceptor to do this we need elf module and providers array in module metadata and as you can see I have HTTP interceptors provider and I use class for my token interceptor and I also say multi true which basically says that this is multi provider which means that we can have multiple HTTP interceptors we already know how to write authorization service and make use of router guards we also know how to use HTTP interceptors to add tokens to our requests now it's time to explain a refreshing process but before we do that let's first understand how JSON web tokens actually work JWT tokens are self-contained tokens that securely represent claims for example the fact that the user has an admin role between parties in our case those parties are client and server that's why we attach tokens to authorize requests to the server so-called self-contained means that the server does not store tokens anywhere it just decodes the information inside of them we can use JWT io website to the code JSON web tokens manually letting past our JWT here so we see three sections header payload and signature the header contains the algorithm used to generate the token and the type of the token payload in our case contains username role issuing timestamp and expiry timestamp after which token is considered not valid anymore signature is used to verify if the token has not been modified after being securely signed by the server with special secret key that should be known only to the server if we modify the token we can see that this signature is considered invalid which means we should not trust this token anymore the self-contained nature of JWT has both advantages and disadvantages on one side it brings scalability to the system because no matter which server of our back-end cluster the query hits there is no need to ask any persistence layer for example database to verify the token but on the other hand there is no way to invalidate the token in case it gets into possession of improper person to alleviate this risk JWT should be short-lived the exact time that the token should be valid depends on the system requirements so now you may ask a question what would happen when the token becomes invalid let's say after five minutes does it force the user to provide his credentials to login again let's see how our demo application will behave if we manually change the value of JSON web token stored in the local storage so here we have our JWT token and let me just randomly change its value now I'm going to refresh the application page and as you see we still have an access to secret random number to understand what happened here let's look at their requests list first we received unauthorized response from the server when the value of the token was one two three obviously not valid token so the application attempted to refresh the token as you see with this API call it passed Refresh token in a request payload and as the result we received new JSON web token that was again issued for the given period of time and after that the query to random API endpoint for the value of random number succeeded so how to implement this in our application when we changed the value of the token we made the server to respond with error code 401 which is HTTP unauthorized response code this caused interceptors error handling logic to execute if the response code of that error is 401 we can make an attempt to refresh the token with handle 401 error method let's take a look what this method does this method is divided into two branches first one for executing token refreshing and a second for blocking and releasing all the other queries that started during the refreshing process which we want to put on hold until we have new JWT token let's analyze the first part we entered this branch if the value of is refreshing flag is false this means that a refreshing has not yet started once we enter this section we said it's refreshing to true indicating that the refreshing has just started next we use behavior subject a refresh token subject and populate the next value of null this will block another request in the second part I will explain it in just a second here we are calling refresh token to obtain new JWT token and once we have it we can indicate back that refreshing has finished setting the flag to false and populate the new token through behavior subject and continue with the request that initialized the whole method but what happens when during the refreshing so after requesting the new token and before receiving it back there are some another queries and our interceptor processes them there is the second part which comes into play now do you remember when we used refresh token subject during the moment when the refreshing is happening the value inside of this subject is now and this filter would block all the requests until the value in that subject is different than no which actually would happen when we get the new token here after that we use operator take 1 to transform it to observable which we'll finish after taking one event from that subject and then we want to release that query that initialized this logic here which means it will only happen once our token is received back during the refreshing process so far we have learned how to use router guards how to implement HTTP interceptors and how to do token refreshing in the last part of this video I would like to show you how you can use passport ejs in your node GS back-end implementation to secure API endpoints with JWT here I have very simple exposure server implementation with a couple of settings and middle words used here you can see the configuration of middleware JWT strategy from passport JS library to check and validate the token based on expiration date now let's take a look how do we do log in log out and talk and refreshing in this node GS application here we have a a log in endpoint we take an username and password for the from the request body but for the sake of this example we don't make use any use of password we just take a username to construct user object again for the sake of this example we just give this user admin role we use jadibooti implementation to sign the token with user payload and with the secret that is this secret password that has to be known only to the server which later is used to verify this token and we also set the time in which this token expires this is 10 minutes 600 seconds then we generate a refresh token which is random string and we store this refresh token in an array with the value of this username which would means that this reference refresh token belongs to this user with the to the user with this username and I will reply back to the client let's see now how we can do logout so here we would just take refresh token from request body and delete it from the are I containing refresh tokens note that in some production-ready implementation those refresh tokens may be stored in some persistence layer like database or somewhere else not in memory as in that example finally let's take a look how refresh method under refresh URL endpoint looks like we will take again refresh token from request body and if this refresh token is in our our i we would take the username under this property inside of refresh tokens array creating new user object for the payload for the new JSON web token sign it give its expiration time and send it back to the user or to the client if the refresh token is not inside of known refresh tokens we would send 401 unauthorized HTTP code finally our random endpoint that generates random value is secured with passport authenticate method with JWT strategy [Music] so that's it for today if this video helped you in any way please click like button and if you want to stay on top of upcoming lessons click Subscribe see you next week [Music]
Info
Channel: Dev Academy
Views: 133,347
Rating: 4.8681111 out of 5
Keywords: jwt, jwt node, authorization json web token, jwt auth, angular jwt, angular login authentication, angular security login, angular login, jwt refresh token, jwt refresh, angular 7 login page example, passport jwt, express passport jwt, router guard, router guard angular, http interceptor angular, jwt angular, json web token, how to implement angular login, how to implement login page in angular, how to refresh jwt token, how jwt token works
Id: F1GUjHPpCLA
Channel Id: undefined
Length: 23min 27sec (1407 seconds)
Published: Fri Dec 14 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.