Angular - refresh jwt token - angularjs

I am having a backend in Laravel and making an app in Ionic. I am using satellizer on the frontend side and this package on the laravel side for JWT authentication. Since I need to have token for users until they log out, I need a way to refresh their token somehow. I am not sure how to do this, would it be better to have all routes requesting auth token and sending 401 response if not present, and then do token refresh, or refreshing a token with timer on the frontend side and how to actually do that?
This is is my routes file:
Route::group(['jwt.auth', ['except' => ['authenticate']], 'prefix' => 'api', 'namespace' => 'Api'], function() {
Route::post('authenticate', 'AuthenticateController#authenticate');
Route::get('user', 'AuthenticateController#getAuthenticatedUser');
Route::get('comment', 'AuthenticateController#comment');
Route::get('articles/latest', 'ArticlesController#latest');
Route::get('articles/by-score', 'ArticlesController#byScore');
Route::get('article/{id}', 'ArticlesController#show');
Route::get('comments', 'CommentsController#index');
Route::get('comments/{id}', 'CommentsController#show');
Route::post('comments/create', 'CommentsController#store');
Route::put('comments/update', 'CommentsController#update');
Route::delete('comments/delete', 'CommentsController#destroy');
Route::post('article/upvote', 'VotesController#upvote');
Route::delete('article/upvote/delete', 'VotesController#destroyUpVote');
Route::post('article/challenge/vote', 'VotesController#challengeVote');
Route::delete('article/challenge/vote/delete', 'VotesController#destroyChallengeVote');
});

What I've done in the past is to do authorization on every request and then do create a new token when the expiry of the token in your database is within some length of time. For me, a 1 hour token would refresh if a user is still active within the last 15 minutes. Then, if the token is refreshed, set the new token inside of Laravel and invalidate the old. Or you could just extend the refresh time in the database. My recommendation would be to have some expire_time set when the token is initially created. And then return a 401 if the token is expired.

Related

What is the flow of using JWT work on the frontend?

I am new to web dev. I built a backend using Django Rest Framework and am using JWT to handle auth.
Now, I want to connect my backend to my frontend in React. But, I am confused how this should be done. Here are my question:
What is the whole flow of requesting and using JWT access and refresh tokens? Like, when should I request a new access token with my refresh token and when should I request a new refresh token? Thanks!
I will make a quick response:
Flow of requesting and using JWT:
A picture worth a thousand words.
The access token is not lasting forever. Whenever it expires, you have to request a new access token with your refresh token.
Refresh tokens can expire, although their expiration time is usually much longer than access tokens. To handle this case, almost all implementations I've seen return a known error code of 'invalid_grant' that you can check for on the client-side and handle by your business. (ex: Show login page...)
Regarding your questions:
What is the whole flow of requesting and using JWT access and refresh tokens?
I don't know you're using what's package about JWT, having too many packages about Django JWT on github (pyjwt, djangorestframework_simplejwt, ...). And Im using pyjwt in my application, because I want to custom my authentication in-app for security.
The workflow:
When FE send request to login/signup APIs, BE generate a token by using JWT, and return that token in the response.
FE store that token on local storage, using it for sending other requests.
BE will take the token by each request from FE to verify. The same as TokenAuthentication of DRF, we must be custom it when using pyjwt. Will verify the JWT token instead.
when should I request a new access token with my refresh token and when should I request a new refresh token?
You can request a new access token after that token is expired.
When you're using djangorestframework_simplejwt you can see the refresh token but in my case (pyjwt), I just need re-generate jwt token again :)
There could be options, but simple flow is next:
You do auth and get access and refresh tokens from a backend and save them as cookies.
You use your access token until you get error 401 because access token has expired
Then you try to refresh your tokens using your refresh token. If you use axios on frontend, good option to write a middleware for this case. This middleware will refresh tokens and repeat a last request. There should be recipes in google.
If success you got new pair of access and refresh tokens and continue your workflow.
If fail, you need to auth again to get tokens.

Do I need to check JWT expiration on client side?

I'm developing website like classified ads with Django REST framework, react and redux. I have a question about authentication with JWT.
I want to use djangorestframework_simplejwt for authenticate and I've checked a few tutorial. I saw that many tutorial are checking access token on client side like below
export function isAccessTokenExpired(state) {
if (state.access && state.access.exp) {
return 1000 * state.access.exp - (new Date()).getTime() < 5000
}
return true
}
and refresh token as well.
But I don't know why. Because just request new access token with refresh token every time we got HTTP 401 Unauthorized error with expired access token.
The workflow that I thought is
Send server a request with access token to get page which only
authenticated user can see.
If access token is expired, frontend
will get HTTP 401 Unauthorized error.
Send server a request with
refresh token to get new access token, then frontend will store it
to localStorage.
Send a request again.
Is this bad way?
My apologies with my poor English...
You shouldnt be checking the JWT on the client side. A JWT is basically a token that the server has given you that is "assumed" valid. When you send the token back, the server will tell you if the token is not valid in the form of Http Status Code 401 - Unauthorized

Handle access token in angularJS

I have Web Api and AngularJS to consume web Api.
when user login with credential user get access_token and refresh token with issued and expires field.
access_token is expired in each 1 minutes and allocate new token to user.
now the problem is
The time between token expired and allocation of new token to user.
if user do a page refresh then its makes an api call to load data of that page, but the access token was just expired and user does not got a new token, so old token is set in header of api call, hence user got 401 unauthorized as response and application throw user to log out.
I am using token in first time so not have much information about access_token and refresh_token
So, I do not know how to handle this situation.
advises is appreciable.
Whenever you make an API call to load data on the page, in the callback you should check the status code. If the status code is 401, get the refresh token and then make another call to the same API and then only initialize the app. Otherwise initialize the app with the old response value.
Thanks #Kushal and #sahil to provide idea.
When user's token is expired app redirect them to login page so on login page added api call to fetch token by user's refresh_token and if user has correct refresh token then assign them to new token and redirect to page which user refreshed by tracking / maintain log of current page of user are. and its working.
Thanks again.

How can i expire my JWT token, when user is idle for sometime(Token based authorization) in nodeJS/Express and Angular

I am generating the JWT token for a user when he logs in with correct credentials at Server side.Previously,I was storing the token in database and for every request I am getting the token from database which leads to bad practice(If i am not wrong).At client side(In my controller),i can store that token in $rootscope so that i can send that token with each and every request.I am unable to find where should i store my JWT token to access at server side for every request??
Some one,suggested me to use Redis to store JWT token.
If i use Redis,can i set maxAge for my token which deletes the token when user is idle for certain time??
Can any one please provide me the suggestions for my procedure?If it is wrong,Suggest me with a right approach!
Note:I am new to NodeJS/Express and AngularjS
JWT's have an exp claim. Set it to the time to which you want the tokens to be valid and have a check in the route if the token has expired.
If it has, send a 401. Else let the route handle the request.
The simplest way:
Add 'validDate' field to token payload when you issue new token for logged user, then check this field when processing the request. If date is expired just return 401 error

In a asp.net web api + angular, with refresh tokens... how do I automatically request a token before it expires

I started using this tutorial to create a application sample, that uses refresh tokens. But in the application, the user have to click in a button to access the token and refresh it with a new token. I wish my application automatically request a new refresh token before it expires. How I can do this?
You should typically keep track of the time the token will expire and then request the new token before the expiration occurs. Requesting early in OAuth2.0 is acceptable.

Resources