Fetching JWT token each refresh - javascript

What my code is doing currently is calling a function that calls an api that gives a new access token every time the page gets refreshed, or to be more specific i have a pinia store that has a function that adds the data to the store when called and this function is being called when the page refreshes.
I am doing this because I have a thing that says "logged in as x" on the navbar and to get that info I go check if the refresh token is valid and fetch the username at the same time.
I'm wondering if this is a bad idea and if I should do it some other way, like storing the username in localstorage/cache/cookies
(sorry for bad phrasing)

Related

How to get the refreshed token in a Linnworks embedded app?

I thought I'd try posting my problem here given the non-existent support that Linnworks provide.
I've created a private embedded app within Linnworks that displays orders in a spreadsheet format. The app is built with Vue.js and uses axios to pull the data from Linnworks APIs. Everything is working as it should be here, except that I'm only returning 100 orders at a time to keep things quick.
I've added a "load more orders" button which appends an additional 100 orders to the end of the sheet, but after a period of inactivity, this causes a "401 unauthorised error" because the token has expired.
Because it's an embedded app, Linnworks store the token within the src of the iframe when the app is initialised, so when it has expired, it doesn't get physically refreshed by the system.
<iframe src="https://example.com/sheet.html?token=9b11e8ff-4791-aca5-b58d-f6da84e996a6"></iframe>
Is there a way of getting the refreshed token without reloading the entire app?
Tokens have a default TTL of 30 minutes, just poll the API with a simple method like /api/Main/Ping to keep your token/session active
I got the following response from Linnworks, which fixed the problem:
After further investigation, this appears to be due to the the pinging of the AuthorizeByApplication call. To help reduce the risk of being returned a 401 Unauthorised "Token has expired. please re-verify the user", it is recommended that when the application is opened, call AuthorizeByApplication and save the response.
Once the session has been created, AuthorizeByApplication should not have to be called again. The token returned in this session has a TTL of 30 minutes. If this token is used in a further call, the TTL of the token is reset back to 30 minutes. Therefore, as suggested in the response of your Stackoverflow question, briefly calling "api/Main/Ping" will reset the 30 minute TTL with little impact on your applications performance.
To Prevent Applications From Using Expired Tokens:
Upon launching application, call AuthorizeByApplication and save session response.
To keep the session from ending, call "api/Main/Ping" using the saved session token to reset the TTL of the saved session.
For any calls made by the application, use the original saved session token.

Reloading or refreshing page removes authorization in vue.js

I'm using social authentication using the vue-google-oauth2 library. It works fine as I am able to authenticate my self and I receive a token from the backend too.
When initially I log in, and by using a function that is part of the vue-google-oauth2 library that I'm using to check if it says that I'm authorized or not, it gives the following response in my browser's console:
this.$gAuth.isAuthorized
true
When I then refresh my browser page, and since I've placed a debugger command in my code, and I print the same function again,
I get the following response:
this.$gAuth.isAuthorized
false
What can I do to ensure that switching tabs, reloading page or refreshing it won't make this happen? Or is this what is actually supposed to be happening?
Have you looked at saving it in as session data? Im not to familiar how Angular state works, but when you set original state you can look for the session key "authorized" and if it doesnt exist set auth to false, if it exists set it to the value.
localstorage.getItem(item)
and
localstorage.setItem(item)
There is also the option of making a component that handles the google auth and sends it to the state.
From the library documentation for vue-google-oauth page you linked it says you need to send that code back to your backend server to create a token to stay signed in, so it's behaving as expected. From here (https://www.npmjs.com/package/vue-google-oauth2#usage---getting-authorization-code) it states :
The authCode that is being returned is the one-time code that you can
send to your backend server, so that the server can exchange for its
own access_token and refresh_token
In other words, you need to do something with that code to make it persist in your app, otherwise it's just a one-time code, so looks to be expected.

How to restore state while changing window.location.href

After a user enters credentials on the login page, a post request is sent to the web server, which sends a cookie (if successful). On the client side, simultaneously, write the user details to my global redux store. On successful authentication from the server, I call window.location.href = 'newURL'. This call reloads my app. Now the user info I stored to the global store is lost, and I am not able to display username which was enetred by the user. How can I access the user credentials?
Thanks in advance :)
As mentioned in comments.
You need to use either localStorage or sessionStorage to keep the data alive.
For eg
localStorage.setItem("user", {"name": "abc"});
Now, though you logged out your data will be there in localStorage and you get the data using
localStorage.getItem("user");
If you want to remove then
localStorage.removeItem("user") or window.localStorage.removeItem('user');
Same applies to sessionStorage as well

Find out If user is loged in (Laravel) in frontend

so I come to you with a simple question: how is laravel session relay working.
My use Case: I have a laravel site cached with a varnish like so :
every get request is made as the user is not logged in
any user related info if loaded via ajax after the user loaded the page.
My problem is that I need to know in my front end if a user is logged in.
Things that I noticed:
Laravel session is not accessible in js
Laravel session is there even if the user is not logged in
I also tried to set my own cookie on login and unset it in on logout, but it my cookie is randomly diapering while the user is still logged in.
If someone has any idea on how to find out if my user is logged in from the standard cookies I would be so grateful.
You can pass the data to JS like I'm showing in my repo. For example:
<input id="authenticated" type="hidden" value="{{ auth()->check() }}">
And then get the data which will be true or false:
let authenticated = $('#authenticated').val();
Alternatively, you could use an Ajax call and execute auth()->check() in a controller method.
You can use in JS var userCheck= " <?php echo Auth::check();?> "; , then check if userCheck is equal to one then user is logged In otherwise not.
you can generate a token whenever a user is logged in and send it to the front-end and save it in the cookie. The cookie can have and the expiry time of say 5 hours. If during these 5 hours, user sends some requests, then the token is refreshed and 5 hour time starts again. In case, no request comes to the backend it means user is not active and you can log him out.

ReactJS - how to setup login pattern?

I'm sorry if this question is a bit vague, but I'm tackling this problem for the first time and any pointer would be useful.
I am building a web app using ReactJS and I need a login system - first page with two fields username / password and submit button. The server returns a token (1234) and this needs to be used in an auth header (Authorization: Bearer 1234) in order to access the protected area.
How should I handle the login and make the browser update itself with the new content available after login?
As the others have pointed out, it is a good idea to use React-Router.
I think you can use pattern like this: You get user inputs and send them via AJAX (with JQuery, Superagent, whatever you want). If the input is valid and user authenticated, the server sends back token with some user info, which can include his roles or permissions. Based on these received data, you can use React-Router to render other component, e.g. welcome page (by calling replaceState on React-Router history object - in flux action for example).
Additionally, you should save this token in a cookie or into a session/local storage (in order to be able to use it on every subsequent request), and the user info could be stored in a Flux store. After saving this user the store emits change event, which should lead to rerender of your root component with the user information you got.
Then, based on the new user roles or permissions in your store, you can have for example ES7 decorator on some of your components deciding, if it displays the actual component or not.
Hope it helps you a bit.

Categories