How to refresh/keep token activated for Mobile Apps - mobile

As far as web applications are concerned I know I can refresh/reissue the JWT by setting another parameter expireUntil in JWT with some duration and check it in each subsequent request and if it's not expire I can reissue the token or something along those lines. I don't know how efficient it is or if it's the right approach but that's the one I had in mind. Secondly I could also do it on the front-end by keep looking at the expiry time and resend the request to reissue it if it's about to expire. Anyway, the idea is to not let the user sign off if it's continuously making requests like in old session era.
Apart from that, the major question is how mobile application keeps the token alive forever. I don't think I was ever signed out of my Uber or foodpanda app even if I'm offline for days. How do they do it in case of mobile apps? Do they simply set the token expiry to some really large arbitrary value or some other way to authenticate and reissue the token because I know I can't do that with the approach I listed in above paragraph as if the user remains offline for a day my token will expire.
Any ideas how can I do that?

Related

Secure JWT token handling in React

I have been searching for a satisfying answer for an hour and I still can't figure out the answer to the question: how to securely store the JWT token on the client side with React?
From what I have read, the localStorage solution in undesirable as it's accessible from third-party scripts. A more secure solution proposed is to use a HttpOnly cookie, but the problem is, it is inaccessible via js, hence it is useless in React.
Therefore, how can I securely store a JWT token on the client side?
In short - you can't securely store token in the browser. If your code has access to the token, then any attacker can also get access to it. That said you can mitigate some risks and decide on a solution which might be "secure enough" for your needs.
E.g. it might be enough for you to keep tokens in the local storage, if losing such a token does not pose a great risk - maybe the data handled by your website is not sensitive.
A viable option is to keep the token in the memory. This way it's a bit more complicated to steal it. Then of course you need to get a new token every time you refresh the page, but you might use SSO cookies to automatically get new tokens in the background.
If you want to go with current security best practices for SPAs, you should investigate the Backend-For-Frontend pattern. You add a lightweight backend component which handles tokens and OAuth flows, and which uses regular cookie-based sessions in communication with your React app. At Curity we created an example implementation of such a component, which you could use as inspiration: https://github.com/curityio/bff-node-express
You can have a look at this great video: https://www.youtube.com/watch?v=lEnbi4KClVw where Philippe de Ryck goes into detail of why it's not possible to securely store tokens in SPAs.

Mapping access token to client IP

My Setup
I am using React and Django as frontend & backend. For authorization purposes I chose Django-rest-knox, which works via tokens stored in a database.
My Problem
Now if an attacker gets a hold of the token (stored in local storage on the client side after a login), he can do anything that the user is able to. There is some expiration on the token and the ability to destroy all tokens of the user by the user himself. But I'd like to be on the safer side.
My Solution
My idea is to map all tokens to the IP address (of the user) that was used to login. That way the token would only be usable on the machine that was used to login. That token-to-IP-address relation would be checked on the backend.
My Questions
Is the idea feasible at all or is there anything in the nature of those IP addresses that breaks my intent?
What is the best way to get the client IP-address?
Do you think that is a secure approach?
Thanks for the help!
The idea is feasible but not efficient. The main problem is, not everyone using static ip address and this will cause you a big feedback by your users because everytime some user's ip address change(via modem reset, power cut, provider problems etc.) he/she/it will have to be authenticated again.
You use 'HTTP_X_FORWARDED_FOR' meta for almost all backend framework as well as django. you can check this link. How do I get user IP address in django?
This idea may come with security but i ll give you a better one that i am currently using on my own application.
My solution: Refresh tokens. With refresh tokens, every time an access token expire(avarage 15 min ideal) user will request a new access token via his/her/its refresh token. With this way even an attacker get user's access token, he/she/it will be only available for 15 minutes(you can make 5-10-15-... mins as well)

Authentication for single-page apps

Background
I am looking at the OAuth 2.0 Implicit Grant flow where a user is redirected to an authentication service and a JWT token is sent back a Single Page Application(SPA). The token is stored in a cookie or in local storage and, in the examples i have seen, the application will hide/show certain pages based on whether it can find the token in storage.
Issue
The problem is that in all the examples (official from service providers), i was able to manually add any random but properly formed token to the browser's local storage and got access to the 'secured' pages.
It was explained to me that you cannot validate the token in the SPA because that would require exposing the client secret and that you should validate the token on the API server. This means that you can 'hide' the pages but it is really easy to see them if someone wants to. Having said that you are unlikely to cause any real damage because any data retrieval or actions would need to go through the API server and the token should be validated there.
This is not really a vulnerability but the documentation and examples I have seen do not explicitly cover this nuance and i think that it could lead naive programmers (like myself) to think that some pages are completely secure when it is not strictly the case.
Question
It would be really appreciated if, someone who is better informed than i am, confirm that this is indeed how SPA authentication supposed to work?
I am far from an expert, but I have played a bit in this space. My impression is that you are correct, any showing/hiding of functionality based solely on the presence of a token is easily spoofed. Your SPA could, of course, get into verifying an access token.
But that may just make it a little more challenging to spoof. If someone wants to fake the client into thinking it has a valid token, they can likely manipulate the client-side JS to do that. Unfortunately that's the nature of client-side JS. Much of the code can be manipulated in the browser.
Thus far this is speaking to protecting the user from seeing a UI/UX. Most applications are only beneficial when they have data to populate their UI. That's where the API access token strategy is still sound. The server will verify the token and not give the client any data without it.
So while it's unfortunate that JS can be easily spoofed and manipulated to show things the developer would rather not make visible, this isn't typically a deal-breaker. If you have some awesome UI feature that doesn't need data, and you need to secure access to that UI itself, this model may not be the greatest.

Mobile App authentication for admin actions

I am developing an application where users are playing a game and upon completion their results are sent to my back end through a POST request. Since I do not want this POST request to be done manually by someone who finds this endpoint (and mess with his results), I need a way to restrict it so that it can be done only through the application. However is it safe to hardcode a token that provides this access?
What is the correct way to go around this problem ?
I would not recommend to use hard-coded tokens, if the token gets compromized, you have to change the server as well as the client.
I would recommend some sort of auth mechanism as JWT with ssl with one rudimentary username/password system.

How to detect expired user session in a react app?

I am developing a REST API based on Node / Express and a frontend for it based on React / Redux. Users can login (which gives them access to additional functionality) but they can use basic functionality also without logging in.
When a user logs in, the client makes an HTTP call with the credentials, the server creates a session and returns a user object (user_id and some other data) as well as a session cookie. The React app saves the user object in its Redux state. In subsequent HTTP calls, the user is authenticated through the cookie.
When rendering the user interface, the React app determines whether it is logged in or not by checking for a user object in its state. This is used to grey out some buttons which are only available to logged in users, or to hide the login link when the user is already logged in.
The problem
It could occur that the session expires, or that the user logs out in a different browser tab. The React app has no way of knowing this and thinks it is still logged in (i.e. app state mismatches reality), leading to wrong UI display.
What pattern to solve this?
Put a hook on all Ajax calls to check for 401 and update the
state?
Return session state in HTTP headers (and then?)
A Comet pattern for the server to notify the client that it has been logged out? (not a REST API anymore then)
Additional calls before actual API calls to make sure user is still logged in? (seems wasteful)
And how to deal with this once the client detects it is no longer logged in during an ongoing operation? I'd prefer to handle this in one place rather than all functions making API calls...
I'd be thankful for some best practice!
There are two straightforward ways to deal with this issue in a React application that I can think of. Both inspired by a colleague of mine few days ago.
Use SSE (server-side-events) technology to PUSH notifications. As you correctly pointed out, this makes your API less pure. This approach should be quite an acceptable sacrifice where flawless UX is required AND/OR your server might need to push other notifications to the app.
Establish a short term timer somewhere in your client app (e.g.: setTimeout(...)) that makes periodic calls to a "ping" API endpoint that will return current user/session information. This approach will impact UX for the duration of timeout, often negligible, and is commonly known as polling.
Hope this helps!
As an alternative to the naive polling, you can make it a little smarter by adding an endpoint that lets you know in how many seconds timeout is set to occur for the session at that point in time.
Then ping just before that time (instead of at a certain poll-rate) and update accordingly.
Logging out in another tab would return with an invalid token so would be picked up, too, but not as quickly if this is your main concern.
For this you could use broadcasting to let the other tabs know immediately (or use sessionStorage's change event to simulate a broadcast on unsupported browsers).
Otherwise the best way would be to implement a ServiceWorker; these can handle all requests for your app to the server. It's a centralised piece of code separate from your app that can broadcast to all tabs that a session is lost the moment it sees that one of its requests was rejected, and you can efficiently naively poll from this one place (instead of in each individual tab's runtime).
Since I am using token from the API Server that is valid for a specific period of time. So in addition to setting token in session storage I was thinking of setting up another session storage variable that stores the timestamp at which the token was generated. Then, in my js code I plan to add the validity period (say, 3600 seconds) and check if the token is still valid or not. If it is valid then the user session is valid else it is invalid.

Resources