ADFS 3.0 using OAuth and Persistent Refresh Tokens - authentication

Question 1
We are currently using ADFS and OAuth (using Windows Server 2012 R2 with ADFS 3.0). Our test applications (both WPF and mobile apps) can successfully authenticate and get an Access Token and a Refresh Token. We can after that continue to use the Access Token until it expires and after that use the Refresh Token to get a new Access Token.
So far so good, but the problem is when the Refresh Token expires, we need to force the user to enter their credentials again. Our aim is to have the user to only enter their credentials once and then use a short lifetime for Access Token and a Persistent lifetime (or really really long) for Refresh Tokens.
According to some blog posts when using a Refresh Token you should get a new Access Token and sometimes also a new Refresh Token, but in our case we never get a new refresh token, so that one eventually expires.
Is this even possible using ADFS 3.0 and OAuth to have a persistent Refresh Token? or get new refresh tokens from time to time so that the user doesn't have to enter their credentials again? or is it possible to have a really long lifetime for refresh tokens.
Question 2
There is also a lot of different properties you can set in ADFS that we are not sure of
TokenLifetime - This is the access token lifetime? what is maximum value?
SsoTokenLifetime - This is the refresh token lifetime? what is maximum value?
PersistentSsoLifetimeMins - what is this?
PersistentSsoEnabled - I guess should be set to true to have refresh tokens working

This post describes a semi-official answer. Here's an example of setting the required values -
Set-AdfsRelyingPartyTrust -TargetName "RPT Name" -IssueOAuthRefreshTokensTo AllDevices
Set-AdfsRelyingPartyTrust -TargetName "RPT Name" -TokenLifetime 10
Set-AdfsProperties -SSOLifetime 480
For the specified RPT, this would issue access tokens with a lifetime of 10 minutes and refresh tokens to all clients with a lifetime of 8 hours.

The only semi-official guidance I have been able to dig up is this slideset:
http://www.oxfordcomputergroup.com/wp-content/uploads/Access-the-future-Alex-Simons.pdf
which states:
Configurable Refresh token support
Lifetime:
workplace joined device 7 days (PSSO lifetime)
Non-workplace joined device max. 24 hours.
Persistent refresh token support in ADFS sure would be nice, but it seems they see the feature mostly as a tie-in to their mobile device management offerings.

Related

When to retrieve data from API again? (Token)

Working on a very basic React-Native App with a login-form, fetching Data from an API and display it. (Token based OAuth2 with Password Grant Type)
Question: When is the best time to retrieve data from my REST service again?
Currently I only fetch the data once, and that is when the user logs in.
Possible Solution: My idea would be to save the user data (username,password | token) in AsyncStorage (or SecureStorage) and to query it again every x minutes - Is that the normal workflow or do I have a major security gap?
I did not include any code, because it is a question of understanding and I shouldn't have any problems with the programming part.
Storing user password is a big NO.
If your server is using standard OAuth2, normally the sign in response would include an access token and a refresh token. See the standard doc.
The access token is embedded in the app's requests to the resource server in the session.
The refresh token is used to retrieve a new access token, either when the current access token has expired, or when a new session is started. So this refresh token is what the app should save, across sessions.
The refresh token's lifespan should be reasonably long such that the client, in this case your app, doesn't have to worry about redoing user sign in.

Revoking JWT with No Expiration

I'm looking to employ token-based authentication for a mobile app that keeps the user logged in as long as they have not logged out. My approach is to create a JWT refresh token when the user logs in/signs up; This token never expires, and continues to refresh 20 minute access tokens.
The problem arises when they log out. I've read the best way to go about this is to blacklist the JWT on Redis to store revoked keys. However, since the JWT never expires, the record can never be removed from Redis and can start to chunk a lot of my memory.
Should I be worried about this, or is Redis memory-efficient on this respect? Is there a better way to revoke JWT with no expiration?
A JWT token is a self contained token. That means that it lives on its own until it expires and can't be revoked. So by definition it must expire. Because when it falls into the wrong hands, it'll give access to your resources without being able to revoke it. So yes, you should be worried with this implementation.
The problem here is that you trust the refresh token itself, because it's a JWT. You should in fact trust the server. Not because the JWT can't be trusted, but because the refresh token doesn't have to be a JWT.
Save refresh tokens in memory including the expiration time. You can remove expired tokens from memory. This means that only tokens that exist in memory can be used to request a new access token. And to be on the safe side, use one-time only refresh tokens.
The flow would be something like this:
the user logs in, receives a JWT access token (5 minutes) and the refresh token 1 code (48 hours). Refresh token 1 is saved on the server.
five minutes later: the access token expires
a new access token is requested using refresh token 1.
user receives a new access token (5 minutes) AND the refresh token 2 code (48 hours). Token 1 is removed from memory and token 2 is added to memory.
and this goes on for several hours.
For two days the user doesn't use the app
50 hours later: because both tokens are expired, the user has to login again. Resetting the flow.
On logout remove the refresh token from memory. And if in the meantime you wish to revoke access. Simply remove the refresh token from memory. Within 5 minutes the user has to login again.
JWT also needs to be revoked as best practice.
Yes, JWTs are self tokens and expirations already part of themselves.
But if user logs out and still their JWTs are not expired means someone can use that token to call different APIs. So it is a security breach.
To avoid such things we should maintain JTI claim of that JWT in our backend with the same TTL with the value of JWT "exp".
When the user logs out we have to clear those JTIs and notifcy the API callers about this just putting into some event service from their API Gateways should get to be notified and clear their side cached tokens if anything and cross check with identity system (Introspection).
This is we have to design the system to avoid further security related issues.

How to Oauth Get Access Token with No Expiry in Google Dialogue flow API

Normally Google Access token is valid for one hour but I want to set it to no expiry. How can I do that, please help
Google access tokens are only good for one hour this is Oauth2 standard and can not be changed. You will need to use a refresh token to request a new access token. No idea if that is possible with dialogflow you will likely have to request your user authenticate again after an hour.
OT: Thats an impressive app you are working on if your users will be using it beyond the access token limit.
According to [1], OAuth token maximum lifetime is 1 hour (3600 seconds) and it cannot be changed.
If your intention is that your application may continue working without having to "manually" recreate a new token, then you could try creating a session client that scopes to multiple requests, as described in the Best Practices Dialogflow reference [2]:
"To improve performance, you can use a single instance of a session client object for multiple requests. The session client reuses the same access token for as long as it is valid (typically one hour). Once it expires, the session client refreshes the access token automatically, so you don't need to recreate the session client to refresh your access token. Your request that also refreshes the access token can take an extra second or two".
Please, try this and let me know the results.
[1] https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth
[2] https://cloud.google.com/dialogflow-enterprise/docs/best-practices

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.

Can LinkedIn's access token renewal flow be performed on the server?

In the Facebook's Graph API, once we have initially authenticated the user, we can interact directly with the API (from the server) to obtain a long-lived page access token. This long-lived page access token never expires. (https://developers.facebook.com/docs/facebook-login/access-tokens/)
In reading LinkedIn's documentation, it appears that it is impossible to obtain an access token with an indefinite (non-expiring) access token. It seems that they expire every 60 days. However, these access tokens can be refreshed before the 60 days is up.
What isn't entirely clear from the documentation is whether or not the access token renewal can be performed on the server alone without the client's interaction. The language of the documentation suggests that the interaction of the client (browser) is required, but nothing is explicitly stated.
So, my question is, is it possible to renew a LinkedIn access token using the server alone, without the interaction of the client (browser)?
Relevant LinkedIn reference material: https://developer.linkedin.com/documents/handling-errors-invalid-tokens
As it turns out, the access tokens of linkedin can not be refreshed without having linkedin user logging in to linkedin. Please refer to the first comment here by LinkedIn employee which clearly states a note that "this refresh will only work if the user is still logged into LinkedIn (authenticated) and the current access token isn't expired. Otherwise, the user will be presented with the login dialog again."
I guess that is now a major issue for those who were previously storing the linkedin access tokens to database for later use.
I am mentioning few links here which refer to the issue with refreshing linkedin oauth2 tokens (hope this makes it clear for everyone who is struggling with the same issue):
1) This refresh will only work if the user is still logged into LinkedIn (authenticated) and the
current access token isn't expired. Otherwise, the user will be presented with the login
dialog again.
2) There is no way to refresh the token using the old authentication token/secret. User
needs to log into linkedin in order for you to refresh the tokens. We use this flow as it
protects our members and their data in the best possible manner.
3) Refreshing an access token is very simple and can happen without an authorization
dialog appearing for the user. In other words, it's a seamless process that doesn't affect
your application's user experience. Simply have your application go through the
authorization flow in order to fetch a new access token with an additional 60 day life span. When the following conditions exist:
-User is still logged into Linkedin.com
-The current access token isn't expired (within the 60 life span)
We will automatically redirect the user back to your redirect_uri without requiring them to reauthorize your application. If they don't exist, we'll prompt them to login and then redirect
them.
4) We have also standardized the duration of the authorization tokens. Previously, members
could choose to grant tokens that were as short as one day or as long as forever. Now all
tokens are 60 days in length, with the ability for you to extend them in a series of rolling 60 day increments whenever the member comes back to your application. To prevent a bad user experience in your application, be sure to proactively refresh tokens and elegantly route any expired tokens through a refresh flow.
5) As long as the user is logged into LinkedIn and their current access token hasn't expired, you can fetch an access token with a 60 day lifespan the next time the user comes to your application.
I had the same question and the LinkedIn docs and forum posts are confusing, but I'm pretty sure now that it's not possible to do it programmatically without user intervention (i.e. the user needs to login to your app via LinkedIn auth to refresh the token).