How to increase the security of your application with JSON Web Tokens — JWT (Rails and React)
Welcome to the third part of this series! If you are following this post, I hope it’s been helpful for you.
If you are new in this blog series, here are the two first parts:
Last thing we did was checking the authorized method, saying if there’s a user or not, and gives all the controllers the access to the current_user.
Now, let’s dig a little deeper in the decoded_token:
Ok, there’s a lot going on here, but don’t worry, we are gonna go step by step.
First, decoded_token uses a helper method auth_header to check if the request that was sent by the frontend has a header with the key “Authorization”. Here’s an example of a fetch request with this header:
So, auth_header is a checker method that returns this header.
As we can see, the key Authorization points to a value of a string the is `Bearer + token`.
So in the decoded_token, token is the second part of this string, splitting on the space (“ ”).
Then we have a code block begin rescue, this is just a check code block.
token_after_decode will use the BCrypt gem to decode the hashed token and return the token, utilizing the algorithm used when we issued the token, as well as the secret we gave for our application.
So token_after_decode will have the user_id and the issued_date.
The issued_date is the second key of this token, so token_after_decode[‘issued_date’].
Now we have access to the time the token was issued, next, we use the method token_issued_less_than_third_minutes_ago?:
This method takes our issued_date and compares with Time.now.to_i (same way we used for our issued date, in seconds). If the time is less than 1800 (30 minutes), it returns true (the token is fresh), if the token is “old”, returns false.
So this is the end of our decoded_token, if the token is still valid, returns the token_after_decode, otherwise, returns nil.
This token will go to current_user to find the user, as we already know.
Now, the last part is, we know that is an authorized user in our application, when that happens, we issue a new token and the user is authenticated for 30 min more:
We send this brand new (and fresh) token, and the user has 30 more secure minutes to use our application.
And don’t worry, every time the user still have an valid token and uses our app, we are sending a new 30 min token!
And that’s all for this series, now we have a more secure app and a better understanding on JWT and communications between Rails and React.
I hope you enjoyed and see you next week with a new topic!