In token-based authentication, how does the application server know which tokens are valid? - authentication

I'm trying to understand cookie vs token-based authentication. I get the basics - cookies have to be stored in the server (as well as the client) to be verified each time, whereas tokens only have to be stored on the client-side. The server simply decodes any incoming tokens and verifies the request.
What I don't understand is, how does the server know whether any decoded token is valid, if a list of valid tokens isn't being stored anywhere in the server?
https://dzone.com/articles/cookies-vs-tokens-the-definitive-guide
User enters their login credentials.
Server verifies the credentials are correct and returns a signed token.
This token is stored client-side, most commonly in local storage - but can be stored in session storage or a cookie as well.
Subsequent requests to the server include this token as an additional Authorization header or through one of the other methods mentioned above.
The server decodes the JWT and if the token is valid processes the request.
Once a user logs out, the token is destroyed client-side, no interaction with the server is necessary.
To be specific - I'd like to know how #5 works. Thank you.

A full answer to your question would be very long, but here is my attempt at a brief one. The server also happens to be the entity which issues the JWT in the first place. As such, it possesses a key which it used to sign each outgoing JWT. As a result of this, when the server receives an incoming JWT, it first tries to open/unlock that JWT using its private key. If the JWT were tampered with in any way, the server might not be able to open it properly, and it would result in an exception. As an example of one sanity check the server would perform against an incoming JWT, it would observe the checksum of the JWT, would not pass in the case of tampering.
Once the server has opened the JWT and deemed it to be valid, the next thing it would likely check would be the exp claim, one of possibly several claims which are contained within the JWT. The exp, or expiry, claim, records for how long the JWT is valid. Should a user present a stale JWT, the server would immediately reject the JWT as being invalid.
So far, we have been discussing checks the server may perform using no state, that is, relying only on the state contained within the JWT itself. In reality, most of the time the server would in fact be storing some state of its own. As an example of why this might be necessary, consider the edge case of a user who logs out of the site or app. In this situation, his phone or browser would still be bearing a JWT with a valid exp expiry. In order to prevent the user from continuing to use this JWT, the server might maintain a blacklist of JWT which it will not honor, even if the exp and checksum pass inspection. So, a third step after unlocking the JWT and checking exp might be to make sure that the JWT does not appear on the blacklist.
A good JWT implementation can limit the amount of server side state to something very small, but typically the server would actually maintain some state of its own.

Related

Refresh tokens: security & implementation

When a user is authenticated by the server, the server sends, according to the most common implementation I found(which is were my question stems from), sends BOTH access token and the refresh token to the client.
-- My first questions is:
What is the point of sending both tokens to the client if, to my understanding, we have the refresh token in the first place to help us mitigate the consequences of an access token being leaked?
If both tokens are sent to the client and are stored together (in the same place, localStorage, sessionStorage, one in former, one in latter - I don't think it matters to the questions how we decide to store them on the client), if an attacker manages to steal the access token, then it is safe to assume he would also find a way to steal the refresh token from the same client since they are most likely stored together. I don't understand why most implementations and answers I find online mention sending both tokens to the client since its basically like putting all eggs in the same basket.
(A big part of my confusion comes also from the fact that those answers and implementations don't mention anything about storing the tokens in HttpOnly cookies, which I'd think would be a common practice if we want to prevent tokens getting leaked, so I'm getting a feeling I'm missing something)
-- My second question would be:
Would it be a correct solution then to persist the access and refresh tokens upon issue in an "accessT <-> refreshT"(like a key=value pair) table on a server, so that only one token is ever sent to the client - the access token? And when that access token expires the process of "refreshing" would be the following:
ResServer = resource server
AuthServer = authorization server
The request with the expired token is sent to the ResServer.
ResServer checks and sees that the access token has expired.
ResServer then sends a request to the AuthServer to look up the refresh token by the access token in the table mention above.
If AuthServer finds a refresh token by using the expired access token as a key - good, AuthServer generates a new access token.
AuthServer then responds to the ResServer with that new access token.
Having received a positive response, ResServer proceeds on with it's usual flow for authorized users.
^^ This seems to me to be a more rational way of keeping the refresh token safe - making it serve its primary function, which is why I don't understand why most other implementations on the web always mention sending both tokens to the client.
-- And my third question is:
Not having much experience implementing microservices, I am confused about why we would ever prefer to implement this token back and forth approach, when, from what I understand, the entire point of tokens is that they are supposed to be a stateless solution(well, the refresh token is always kept on the server regardless of implementation, which confuses me even more about that "stateless" part). Doesn't it make more sense to just use cookies that basically serve the same function, but are easier to implement, secure by default("Secure", "HttpOnly" flags), and, as it appears to me, are much easier to revoke in can they are leaked?
Thanks you for taking your time to read this entire post, I appreciate your help.
Regarding your first question:
The advantage of having two tokens is not that you can store one of the tokens more securely. The advantage is that if the Resource Server gets compromised, it does not allow lateral escalation. For this to make sense, your access tokens must be bound to specific resource servers.
As an example, assume you have two resource servers ResA and ResB. Then your Authentication server would allow you to obtain one access token for each of these servers, and one refresh token (that allows refreshing both access tokens). If resource server A gets compromised (or the network path between the client and that server), then the access token to that server will expire at some point, and the attacker will not be able to access resource server B with the access token issued for resource server A. At the same time, only the legitimate user is able to refresh their tokens, since they only provide the refresh token to the AuthServer, such that a compromised or malicious resource server never sees at.
That leads directly to your second question:
Your proposed model prevents key rollover. If a resource server gets compromised, all its tokens are eternally compromised, unless the Authentication Server voids all refresh tokens. Voiding refresh tokens would lead to users being logged out of all resource servers (even those who are not compromised).
As an example, consider the following scenario: Tour authentication provider is a large public service, such as "Sign in with Google", with thousands of resource servers using this service. Now one of those resource servers gets compromised, and attackers steal the authentication tokens.
In the commonly employed auth-refresh token pattern, the auth tokens will expire, which means that the service will be inaccessible for attackers as soon as the used vulnerability is fixed + the time it takes for tokens to expire (since the attackers could not get hold of the resource tokens), without the need for the AuthServer to do anything. Additionally, the AuthServer does not need to keep track of the issued tokens, if it uses cryptography to sign the tokens with a private key only known to the auth server, as it (and all resource servers) can trivially verify token authenticity by validating against a public key (please also see the end of my answer).
In your proposed approach, the AuthServer (which is Google in this example) would have to void all refresh tokens OR they would have to selectively delete all auth-refresh token pairs for the affected resource server from the key-value store. That key-value store will be gigantic, since it has to contain EVERY auth token ever issued, for any service that uses "Sign in with Google", and apart from storage costs, this delete operation will take quite some time.
Regarding your last question:
You can store access tokens in Cookies. There is a bunch of advantages to that (including the Secure and HttpOnly flags that you mentioned). It has two disadvantages: If you want to implement something like a CLI client that runs outside of a browser, you would have to implement Cookie handling. The other disadvantage is the CSRF risk as Cookies are automatically sent on every request. Using local storage prevents this, as an external website cannot access the local storage of your website to extract the token.
In the end it comes down to the concrete scenario, if Cookies or Local Storage + Custom Header are the preferable solution.
However, I think you have a misconception regarding statefulness:
Access and Refresh tokens do not need to be stored on the server. Instead, the Auth Server signs the Token Contents with a cryptographic private key, before sending them to a client. In doing so, the AuthServer includes an expiration date in the token, which is included in the signed content.
To validate the token, the Resource Server (or the AuthServer) checks if the signature comes from the AuthServer's private key, and then checks if the expiration date has passed. In particular, the resource server does not need to communicate with the AuthServer, apart from obtaining its Public Key from time to time. This makes this solution scale really well for very large deployments. See the Microsoft Azure docs, which do a great job on explaining the difference between Auth and Refresh tokens.
What you are alluding to are traditional session ids, which are stored on the server until they expire. Thats obviously a much simpler solution, and works well for smaller, more monolithic applications. It just does not work for hyper scalers.

In JWT, why do you need a refresh token instead of just re-logging in?

I understand the concept of JWT and the need for a refresh token.
As far as I understand, it's to add an additional layer of security so even if the N number of access tokens generated from the fresh tokens are leaked, as long as you keep the refresh token in a safe place (a separate place) it's safe. I get that.
But what I don't understand is, why can't you just do the following?
A client authenticates
The server gives the client an access token.
After a while, the client's JWT expires. The client knows when it expires because it's baked into the token definition.
The client re-authenticates with the server.
The server re-issues a new unique access token.
Doesn't this solve the same problem of a more complex refresh token + access token pattern? I'm sure I'm missing some details. Are there use cases where this model doesn't work (or work)?

Manually expire JWT token from server - WEB API 2

I am working on a api server which revives requests from a mobile app. I am using JWT with ASP.Net MVC Web API 2. In this Admin gives access of various departments to mobile app users. I set these DeptIds in Claims at the time of Login. On every authorised request from app, in a custom action filter attribute I read claims to match deptId in request URL with claims. This all scenario works fine.
Now my problem is, when Admin revokes access of any particular dept from app user, how should I expire the access_token of that user so that, on Login request call, I can set new Claims. Otherwise, as Admin removes access from server but the deptId still exists in user's Claims so user still have access to that department.
One way is on every request, check in database for access but that increases overhead of server also increases response time. So I don't want to go this way.
I didn't find anything on web how to expire token in JWT. Can any one help on this?
A JWT token happens to be a kind of token that allows it to be self-contained i.e. one can validate it without consulting an external entity.
That also means that there's no external entity that will tell you that the token was revoked or expired. Expiration can only happen by some property in the JWT itself; the exp claim was standardized for that purpose: it will tell the recipient the time after which the information in it must no longer consider to be valid
Authentication and Authorization are different things.
Use JWT for Authentication but not for Authorization. I mean that using JWT you can know who the user are but don't put information about what user can do into the JWT. Check permissions for the user on the server side basing on just user's identity that you got from JWT. You may also put into JWT some information that additionally limits access rights (i.e. blacklisting; for example, social network site creates an access token for a game to access my identity and friends list but not my posts) but don't put there information that directly provides access to some features (i.e. whitelisting). In that way you can easily remove access to some features on your sever-side despite that fact that the user is already logged in with JWT.
I understand you are interested in revoking or invalidating tokens instead of expiring them.
Revoking or invalidating tokens
Unfortunately​ it's not possible to achieve it
without keeping the track of the tokens somewhere:
Issue a token and add it to a whitelist to keep the track of it.
When validating a token, check the whitelist and refuse the request if it is not whitelisted.
To revoke or invalidate a token, remove it from the whitelist.
This security schema require some trade-offs. Deal with it.
Performance considerations
Regarding your performance concerns: Bear in mind that premature optimization is the root of all evil. You shouldn't optimize until you have a performance problem and you have proven that the performance problem comes from the way you store your tokens.
You could start storing the tokens in the database and then consider a cache in memory, for example. But always be careful when fixing a problem that you currently don't have.
Token identifier
The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it's valid by checking the value of the jti claim against the token identifiers you have on server side.
For the token identifier you could use a UUID.

Security and reliability concerns about JSON Web Tokens (JWT)

I'm creating an API along with a SPA for a personal project and I'm hesitating between the following solutions to authenticate users (note: over HTTPS):
HTTP Basic Authentication (send username/password wich each request)
Token based authentication (store SHA1-ed user tokens in the database)
JSON Web Token (JWT) authentication
I don't even consider OAuth cause it seems like a real pain plus I don't need to authenticate with other apps, I'm only concerned about authenticating users.
From what I've read, JWT seems to be a growing standard. It basically holds the caller's data so everytime he makes an API request you encrypt(base64(header) + "." + base64(payload)) with your secret and you compare it with the signature provided in the last part of the token itself. It avoids having to perform DB transactions.
The problem is that if I use JWT 1) I have no possibility to manually revoke specific tokens, and most of all 2) if I change a user's permissions, the previously granted JWT will still have the old data with his old permissions which could grant/restrict him continuous access to some data as long as he doesn't get a new token with his new permissions, which is really problematic and I'm surprised I haven't seen anyone mentionning this problem yet. Moreover, 3) JWT claims to allow the server to validate access without having access to DB but I can't imagine any API request that doesn't involve the database somehow, if only to return data the user asked for. So this argument doesn't make any sense to me.
To me, my best option right now is option 2. Website will have restricted and small traffic so storing tokens in the Database seems like a small and worthwhile trade-off and allow me to do anything I want with these tokens, including managing their lifecycle and permissions. It also avoids exposing the users' credentials like in option 1, in case they use the same ones for other online services.
I just want to know if my concerns about JWT are right or if I misunderstood its functioning? Also, even if I've already read a lot about these different options, feel free to link anything that could enlight me and help me make a better choice. Thanks.
You are right and invalidating tokens before expiration time is a common JWT problem. There are several reason to consider: account deleted/blocked/suspended, password changed, permissions changed, user logged out by admin.
With JWT, you can also set a token blacklist to store tokens that were between logout & expiry time, mark expired and check it in every request. You can include only the ID (jti claim of JWT) or use the last login date and the iat claim (issued at)
Other technique to invalidate tokens when user changes their password/permissions is signing the token with a hash of those fields. If the field value changes, any previous tokens automatically fail to verify.
See https://stackoverflow.com/a/37520125/6371459
Finally, be aware that the token is signed with server private key (not encrypted)
sign(base64(header) + "." + base64(payload))

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.