Do refresh token for same account user is always same? - jawbone

Copied from the old forum:
Every time I register same user to jawbone for allowing me to retrieve data, it is returning same refresh token. If that is always true Can I use refresh token to update user details in my application. As there is not EncodedUserId come in response by which I can identify user.

The refresh token is not guaranteed to be the same forever, so you should not make that assumption.
Additionally, the refresh token can only be used to get new access tokens and not to retrieve any other data.
If you are looking for a unique ID to represent an UP user, you should use the xid retrieved from the User endpoint.
The user's xid is also returned as the user_xid in the meta section of any UP API response.

Related

What is the correct way to create and store JWT refresh tokens?

I am currently attempting to implement auth into my API and am puzzled by the concept of refresh tokens. I understand they are for generating new access tokens upon their expiration, however I am unsure as to what payload they are meant to carry and how they are meant to be stored in the DB.
Several sources have implemented refresh tokens using the same payload as the access tokens (i.e a userId). Others have implemented a session system whereby a session object is serialized and checked upon validation.
My main confusion regards the validation and invalidation of refresh tokens. Are refresh tokens meant to be stored in the DB alongside the user, such that you can check that it is valid (and not being reused)? If so, should it be deleted from the DB when a new refresh token is generated? If this is the case, how do you allow for multiple sessions across several clients? It seems wasteful to store all past refresh tokens or session objects in the DB, particularly if the expiration time of the access token is short.
Apologies for the somewhat rambling question. This topic is one I'm struggling to get a grip of so any help would be much appreciated.
First please understand the importance of JWT token , they are meant to verify the integrity of the user i.e. genuine user.
For this purpose access token are generated and verified at each request to check weather the authentic user is making that request and also these token have expiring time based on your requirement and to refresh them refresh token are used. now lets say your token have very short TTL and you make request to refresh your token with each request of refreshing these token your server has to access DB and refresh the token , if you have store serialized object in token then it would add another business logic to deserialize and check for the Userid.
therefore the you should store minimum information in these token access token as well as refresh token , and this refresh token you should store along side user with minimum information.

Sliding Window with expiring JWT Refresh Token

I'm running a website + native apps that communicate via HTTPS with my backend. The following requirements must be fulfilled:
Sliding session on the website. That means if the user interacted with the website within the last xx Minutes, he must not be logged out
Remember me on the website. When this is checked, the user must not be logged out (or after a very long time)
The user must not be logged out on the app
Access can be revoked, either by the user (currently logged in) or specific events (password changes).
What I currently have is the following: A refresh token endpoint generates a JWT when password hash and username match in the database. Every refresh token has a jti that is stored in the database, as well as expiration (for DB cleanup only), device_id and a revoked flag.
Another endpoint can be hit with the refresh token, which returns a JWT access token. The access token is valid for 15 minutes. The access token cannot be revoked.
My problems arise with requirement 1. I do not want the user to reauthenticate when he's interacting with the website. This means I need the refresh token. However, the refresh token must only be valid for e.g. last user interaction + xx Minutes. I cannot extend the access token with every request, as there is no way to blacklist access tokens. This would mean that a leaked access token is like a master key forever (as long as you constantly hit the api in 15-minute intervals). But I also do not know what the expiration for the request token could be.
The second problem is (2) with incognito modes or multiple devices. Assuming the user opens 20 private tabs and uses remember me on all of them. Then I have to store 20 tokens in the database. I could, of course, set a limit for type "web" to say 5 and "app" to 3 and remove the oldest last accessed one from the database (and therefore invalidate it). But this would log him out on the "main" browser if he opens 5 private tabs somewhere. It would also limit the number of phones to e.g. 2.
Different PCs/laptops would also generate many refresh tokens of type web. How would I best identify the corresponding device so access can be revoked, but I also do not store hundreds of refresh tokens over the application's lifetime? Best would be one refresh token per device (windows+firefox, iPhoneA, iPhoneB, windows2+firefox). But identifying desktop PC's is super hard.
What it comes down to is:
How can I store refresh tokens in the DB so they are identifiable to the end-user (e.g. Whatsapp webs "Safari started in New York last used at xxx-xxx-xxx"
How do I avoid having hundreds of tokens per user in the DB (as refresh token basically never expire, and the user can open as many private tabs as he likes without logging off)
How can I implement sliding windows with the refresh/access token pattern? So no unlimited refresh token on the client-side, but also no logoff after the access token expires as long as there is any usage. I could have it in the session storage, but then it still clutters my database and shows to the user as "currently logged in" (which displays all refresh tokens) as it's basically still valid.
Sliding session on the website. That means if the user interacted with the website within the last xx Minutes, he must not be logged out
To solve this problem you can use a refresh token, i.e when the user login for the first time, the application will return a access token (JWT format), with an expiration date set to the amount that you want.
When the user will browse the application, your backend will return a X-Refresh-Token header valid for your xx amount of time (i.e you'll need to return this header for each backend call).
If the acess token is expired (the backend will read the access token used, and perform check on expiration date token field), the backend will return a 401 Unauthorized error,
and your client must call the authentication endpoint, providing the last refresh token stored, to issue a new access token.
With this implementation your requirement #1 is satisfied.
Remember me on the website. When this is checked, the user must not be logged out (or after a very long time)
To solve this one, you'll just need to generate a long lived access token (i.e with an expiration date set to the amount of time you want).
The user must not be logged out on the app
I don't understand this one
Access can be revoked, either by the user (currently logged in) or specific events (password changes).
This one is really tricky. Since backend is stateless, revoking access token is a really complex topic.
Hopefully a lot of pattern existing to solve this one, we just need to discuss about it.

Update Claim value in User Claims list whenever it is changed in Database

I am using IdentityServer4 Implicit flow for my Angular application. I have permissions claim added to scope list and also it gets populated properly.
i need to update this claim value whenever i change the value in database.
currently, the claim value is refreshed only when access_token is refreshed/renewed.
I want to check/update claims on every call to api.
Two things:
You are mixing authentication with authorization. The permission claims should not be present in the Access token. Please read here why. And read my answer here for some thoughts about a possible design.
You can't change a JWT.
An access token contains information about the client and the user (if
present). It is a self-contained code that can be decoded by the
server only and has a certain lifetime.
Please note that the refresh token does not really refresh the access token, it creates a new token. The original token remains valid until it expires. An alternative is to use Reference Tokens.

Alternate approaches to token based authentication

I have a RESTful API which will be users will reach via a set of web/mobile clients, and I am trying to figure out how to handle token auth. My understanding is that traditional token auth works as follows:
User auths by providing user/pass, receives back a token and expiration
Until , token is passed with every request
Upon expiration, a new token is requested (either by providing a separate 'refresh' token or just by re-authenticating with user/pass)
Is there a good reason not to generate a new token with each request? That is: an initial token is requested via user/pass. This token is passed with the first API request, which returns the content of the api response plus a new token which must be passed with the following request... The advantage to this approach would be that each request (action) the user takes 'resets' the expiration of the token auth such that the token expiration time basically becomes the period of time the user can be inactive without being logged out. Is there a good reason not to use this approach? The approach laid out above seems more commonplace (which is why I ask).
Finally, one only slightly related question. What stops someone who is watching the network from grabbing the token from the user? In particular in the first scheme, it seems easy to do (in the second method, you would need to capture the incoming request and then quickly get the next token before the user does).
From what I read is that you want a sliding window in which a user is authenticated. Every new request within the expiry window prolongs the session.
If I understand that correctly I would suggest an alternate approach; every time a request is successfully authenticated update your store in which you have your tokens and update the expiration time.
This way you don't have to bother your users with all the hassle of grabbing the new token every single time.
So, yes, there's a good reason not to do that: it's not necessary for your use case and only annoys the user.
With the above approach I assume that you have a store (database) in which you keep your tokens + an expiration date.
So the process is this:
The user provides username + password
Create record in store
Give user the token
Update store every time a successful request is made
On a related note; don't give the users the expiration date. That's fine when using cookies for example but that is merely useful as an additional security measure.
On your slightly related question; nothing stops anyone from grabbing the token if you don't use TLS/SSL/HTTPS. Always use TLS (which is SSL, which is HTTPS, more or less).

Is a Refresh Token really necessary when using JWT token authentication?

I'm referencing another SO post that discusses using refresh tokens with JWT.
JWT (JSON Web Token) automatic prolongation of expiration
I have an application with a very common architecture where my clients (web and mobile) talk to a REST API which then talks to a service layer and data layer.
I understand JWT token authentication, but I am a little confused at how I should use refresh tokens.
I want my JWT authentication to have the following properties:
JWT Token has an expiration of 2 hours.
The token is refreshed every hour by the client.
If the user token is not refreshed (user is inactive and the app is not open) and expires, they will need to log in whenever they want to resume.
I see a lot of people claiming to make this a better experience using the concept of a refresh token, however, I don't see the benefit of this. It seems like an added complexity having to manage it.
My questions are the following:
If I WERE to use a refresh token, wouldn't it still be beneficial to have a long term expiration for good practice on that token as well?
If I WERE to use a refresh token, would that token be persisted with the userId and/or JWT token?
When I update my token every 1 hour, how does this work? Will I want to create an endpoint that takes in my JWT token or my refresh token? Will this update the expiration date of my original JWT token, or create a new token?
Is there the need for a refresh token given these details? It seems that If the user is just using a JWT token to grab a new token (per the link above) then the refresh token is obsolete.
Let me come to your questions a little later down the line and start by actually discussing the whole purpose of a refresh token.
So the situation is:
The user opens the app and provides his login credentials. Now, most probably the app is interacting with a REST backend service. REST is stateless, there isn't a way to authorize access to the APIs. Hence, so far in the discussion, there is no way to check if an authorized user is accessing the APIs or is just some random requests coming through.
Now to be able to solve this problem, we need a way to know that the requests are coming from an authorized user. So, what we did was to introduce something called an access token. So now once the user is authenticated successfully, he is issued an access token. This token is supposed to be a long and highly random token (to ensure that it can not be guessed). This is where the JWT comes into the picture. Now you may/may not want to store any user-specific details in a JWT token. Ideally, you would want to just store very simple, extremely non-sensitive details in the JWT. The manipulation of the JWT hash to retrieve other user's details (IDOR etc.) is taken care of by JWT (the library being used) itself.
So, for now, our problem with authorized access is solved.
Now we talk of an attack scenario. Let's say using all of the above user Alice, using the app, has the authorized access token and now her app can make requests to all the APIs and retrieve the data as per her authorization.
Assume that SOMEHOW Alice loses the Access Token or put another way, an adversary, Bob, gets access to Alice's access token. Now Bob, despite being unauthorized, can make requests to all the APIs that Alice was authorized to.
SOMETHING WE IDEALLY DON'T WANT.
Now the solution to this problem is :
Either detect that there is something of this sort happening.
Reduce the attack window itself.
Using just the access token alone, it is hard to achieve condition 1 above, because be it Alice or Bob, it's the same authorized token being used and hence requests form the two users are not distinguishable.
So we try achieving 2 above and hence we add an expiration to the validity of the access token, say the access token is valid for 't' (short-lived) time.
How does it help? Well, even if Bob has the access token, he can use it only while it is valid. As soon as it expires, he will have to retrieve it again. Now, of course, you could say that he can get it the same way he got it the first time. But then again there's nothing like 100% security!
The above approach still has a problem and in some cases an unacceptable one. When the access token expires, it would require the user to enter his login credentials and obtain an authorized access token again, which at least in case of mobile apps, is a bad (not acceptable) user experience.
Solution: This is where the refresh token comes in. It is again a random unpredictable token that is also issued to the app along with the access token in the first place. This refresh token is a very long-lived special token, which makes sure that as soon as the access token expires, it requests the server for a new access token, thus removing the need for the user to re-enter his login credentials to retrieve a new authorized access token, once an existing one has expired.
Now you may ask, Bob can have access to the refresh token as well, similar to the way he compromised the access token. YES. He can. However, now it becomes easy to identify such an incidence, which was not possible in the case of an access token alone, and take the necessary action to reduce the damage done.
How?
For every authenticated user (in case of a mobile app, generally), a one to one mapped refresh token and access token pair is issued to the app. So at any given point in time, for a single authenticated user, there will be only one access token corresponding to a refresh token. Now assume that if Bob has compromised the refresh token, he would be using it to generate an access token (because access token is the only thing which is authorized to access resources through the APIs). As soon as Bob (attacker) requests with the newly generated access token because Alice's (genuine user) access token is still valid, the server would see this as an anomaly, because for a single refresh token there can be only one authorized access token at a time. Identifying the anomaly, the server would destroy the refresh token in question and along with it all, it's associated access tokens will also get invalidated. Thus preventing any further access, genuine or malicious, to any authorization requiring resources.
The user, Alice, would be required to once again authenticate with her credentials and fetch a valid pair of a refresh and access tokens.
Of course, you could still argue that Bob could once again get access to both refresh and access tokens and repeat the entire story above, potentially leading to a DoS on Alice, the actual genuine customer, but then again there is nothing like 100% security.
Also as a good practice, the refresh token should have an expiry, although a pretty long one.
I believe for this scenario you could work with the access token alone, making
life easier for your clients but keeping the security benefits of a refresh token.
This is how it would work:
When your user logs in with credentials (username/password) you return a
short-lived JWT. You also create a db record where you store:
JWT id
user id
IP address
user agent
a valid flag (defaults to TRUE)
createdAt
updatedAt
Your client submits the JWT in every request. As long as the JWT hasn't expired,
it has access to the resources. If the JWT expired, you refresh it
behind the scenes and return both the resource and an additional X-JWT header
with the new JWT.
When the client receives a response with an X-JWT header, it discards the
old JWT and uses the new one for future requests.
How refreshing the JWT works on the server
Look for the matching db record using the JWT id.
Check if the valid flag is still true, otherwise reject.
Optionally, you can compare the request IP address and user agent against
the stored IP address and user agent, and decide to reject if something looks
fishy.
Optionally, you can check the db record's createdAt or updatedAt fields, and
decide not to refresh if too much time has passed.
Update the updatedAt field in the db record.
Return the new JWT (which is basically a copy of the expired JWT, but with an extended expiration time).
This design would also give you the option to revoke all tokens for a user (for
example, if the user loses his phone or updates his password).
Benefits:
Your client never has to check expiration times or make refresh token
requests, all it does is check for an X-JWT header on responses.
You can add custom refresh logic based on IP address, user agent, max-token
age, or a combination of those.
You can revoke some or all tokens for a user.
If I WERE to use a refresh token, wouldn't it still be beneficial to have a long term expiration for good practice on that token as well?
Refresh Tokens are long-lived, Access Tokens are short-lived.
If I WERE to use a refresh token, would that token be persisted with the userId and/or JWT token?
It would be persisted as a separate token on the client, alongside JWT but not inside JWT. UserID/UID can be stored inside the JWT token itself.
When I update my token every 1 hour, how does this work? Will I want to create an endpoint that takes in my JWT token or my refresh token? Will this update the expiration date of my original JWT token, or create a new token?
Yes, you need a separate service that issues and refreshes token. It won't update the expiration of the existing JWT Token. A token is simply JSON field-value pairs that are base64 encoded. So changing the data, changes the output. The token also has the issue date, which will at the very least change on every fresh issue (refresh). So every token will be unique and new. The old tokens will auto-expire, hence you need expiration on all Access Tokens, otherwise they will linger around forever.
The other answer here states that old tokens get destroyed when you issue a new token. That's simply not the case. Tokens cannot be destroyed. In fact, you can harvest hundreds of tokens by constantly contacting the auth server and asking for new fresh tokens using your Refresh Token. Each of those Access Tokens will be valid till their expiry. So expiry is imperative, and it should be short.
Is there really the need for a refresh token given these details? It seems that If the user is just using a JWT token to grab a new token (per the link above) then the refresh token is obsolete.
JWT tokens have client claims. For example is_manager:true claim on a JWT token might allow access to manager-level features. Now if you decide to demote the user from manager to contractor, that won't take effect immediately. The user may still be using the old token. Finally when that expires, he hits the auth server to refresh his token. The auth server issues a new token without the managerial claim and the user won't be able to access managerial features any more. This creates a window during which the user's claims are not in sync with the server. This again explains why Access Tokens should be short-lived so sync'ing can happen often.
Essentially you are updating the authorization checks every 15 minutes, instead of checking them on every single request (which is how typical session-based auth works). If you want real-time permissions instead of every-15-minute refreshes, then JWT may not be a good fit.