Handle access token in angularJS - 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.

Related

What is refresh token and can we control refreshing the ID and Access token in AADB2C?

My team is working on implementing or rather configuring B2C login for our client's mobile app. We got the configuration setup to a point where the user can login to the app once and the token gets cached in MSAL. And next time onwards, the user is able to directly login without entering his/her credentials. We are following the pattern as described here
Our code first tries to retrieve the token using AcquireTokenSilent and if the token is not present in the MSAL cache, then we retrieve it using AcquireTokenInteractive.
I was trying to understand how the ID and Access tokens are refreshed and found on MS docs here about tokens which says
Refresh tokens are used to acquire new ID tokens and access tokens in
an OAuth 2.0 flow. They provide your application with long-term access to resources on behalf of users without requiring interaction with those users...
This also mentioned that when we redeem the refresh token to get new ID and Access tokens, we also get a new refresh token that replaces the previous refresh token.
Now I tried logging out and log back into my mobile app after 1 hour or more and I was still able to login. When I inspected the claims, the ID and Access token expiry was refreshed to next 1 hour of login.
My question here is:
Since ID token and Access tokens have default expiry to 1 hr, then how is it that even though I was logged out for more than an hour, my token refreshed and I was able to login without entering user credentials.
If this is because refresh token automatically refreshes the ID and Access tokens when they approach their expiry, then does this process go on till the refresh token expires itself.
The MS docs also mentioned that when the ID and Access tokens are regenerated after their expiry, we also get a new refresh token. If this is the case then the refresh token would never expire since the new token will always have new expiry.
Is there a way to control the refresh token so that we can control when to refresh the ID and Access tokens.
I am sorry if I missed anything but I am a little confused on how the refresh token works and is there a way to control when to refresh the tokens and when not.
Thanks in advance.
Yes, the refresh token is used to get the new id token and access token, even the id token and access token were expired, as long as the refresh token does not expire, it could use the refresh token to get new id token and access token, meanwhile, a new refresh token will be generated, if you want to configure the token lifetime, you could do that in the portal.
Reference - https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-tokens?pivots=b2c-user-flow

How to use refresh token coming from acquiretoken silent in MSAL-browser

I am trying to acquire token by aquiretokensilent after login and then have to do authorization in multiple modules.As documentation of MSAL-browser acquiretokensilent will automatically take care of refresh token.In network tab also i am able to see refresh token.But how to use it, does it automatically replace access token or do i need to do something extra and how i can see that refresh token in the console converting to access token after expiry of access token.I have read lot of documents but not got clearity how to use it.
A refresh token is used for renewing an access token or request access tokens with other scopes.
This official doc indicated that how a refresh token renews/requests a new access token and a new refresh token at the base layer.
And yes, you should call aquiretokensilent before API call, if the access token exists and it is not expired, this function will reply the access token to you from local cache directly, if not, it will request a new access token by refresh token from Azure AD.
For details, see this doc.

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.

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

OAuth2 grant for interacting between my Angular app and my REST API?

Help me pick the right OAuth2 grant type for my Angular App and my REST API?
UX-wise I want just one login form on my front-end, that would ask for username/pass(no dialog asking for permissions). I think the "Resource Owner(Password) Grant" is the most appropriate for me(since I control front&backend), but I'm not sure how should I handle access token refresh.
Correct me if I wrong about the flow:
When user submits credentials through login form, access token is returned.
I can store this token in LocalStorage to make subsequent Ajax requests with it.
As I understand access tokens should be short-lived. And should be updated with Refresh token. Should the refresh token be returned with the access token after initial login and also stored on the client? If not what is the alternative?
Should there be any session maintained on the server to invoke access token refresh? or I should make calls from front-end to refresh the access token when it is about to expire. But then I need a refresh token on the front-end, right?
As you see there is a mess in my head about refresh token. Would be great to have some clarification or suggestion for another grant implementation.
Backend technology I guess is irrelevant here, but just in case it's Symfony2 with FOSOAuthServerBundle.
When you are calling the TOKEN endpoint (for every grant_type possible) on a OAuth Server, you get an access_token but other information as well (I think there are all here):
{
access_token: // your short-lived token
expires_in: // number of seconds before the access_token is invalid
token_type: // the type of the access_token
scope: // scopes of the access_token
refresh_token: // long-lived token to get a new access_token
}
You need, in my opinion, all these information (maybe the scope is unused, but all others will be used later). You have to store the access_token to ba able to make API calls. After seconds, your access_token will not work anymore. You will need to get a new one. You can either ask the user to log in AGAIN or use the refresh_token.
You will have to call the OAuth Server on the TOKEN endpoint but with a grant_type: refresh_token. You will have to provide the refresh_token from the first request (among other information) and in return you will have the same response as above. In fact, I think you will have to do that every time an access_token is expired. In my opinion, the server side does not know anything about sessions or connected users. It knows about valid and invalid access_token.
This is OAuth. If you don't want to have to refresh everytime, you can make a long-lived access_token (by setting the expires_in), I think this is the only solution that makes sens in an OAuth context.
Do you need some clarification about OAuth in general?

Resources