14 ms·
Why to not use JWT (2021)
- BerislavLopac 4y agoI'm always reminded of this seminal article by our very own @tptacek: https://fly.io/blog/api-tokens-a-tedious-survey/ https://fly.io/blog/api-tokens-a-tedious-survey/
- Zamicol 4y agoDisclosure, I'm the author: If you're looking for something different from JWT, allow me to suggest Coze. https://github.com/Cyphrme/Coze https://github.com/Cyphrme/Coze
- drikerf 4y agoNot saying you should use JWT, but you can invalidate tokens by adding a timestamp to the payload. This way you could invalidate those issued before a certain time and logout users.
- lucasyvas 4y agoThis is unnecessary - expiry time is a first-class capability of a JWT and records the time of expiry, not when it was created.
- drikerf 4y agoYes, but if you want to invalidate say currently logged in users, before the tokens expire.
- lucasyvas 4y agoI suppose, but generally the solution is a refresh token with the JWT having a very short expiry to the point where adding a timestamp would be superfluous. IMO the only flexible way is a denylist of tokens or JTI which adds the burden of more infrastructure. My take is to use an opaque token unless you are using OAuth and paying someone else for all these extra capabilities, at which point things become easy. ex. If you are using Firebase Auth or Auth0, they manage the token revocation for you so the problem sort of melts away and you are left with only benefits of JWT. Just have to blacklist the JTI claim and it'll automatically be denied in the future.
- deleted 4y ago[deleted]
- ehutch79 4y agoThe overwhelming majority of JWTs have an expires field. That's not the issue. The idea is that you have a disgruntled employee with a token that expires in 5-10 minutes. You don't have invalidation checks, so what damage can that employee do in 5-10 minutes? Keep in mind for many companies, exporting a client list is a big deal. Why would you not have validation checks? The point of a JWT is they're stateless. When you get one, if you have the key, you can validate it without access to the auth service. If you take your JWT, and then are using the claims to check the database, it is 100% functionally the same as a session token. JWTs are not something you issue to use on your own service. It's for another service to verify the user on their service based on a factor coming from your service.(yes i'm aware there are other uses) If the only thing in your payload is a session_id or a user_id. Stop using JWTs.
- the_sleaze9 4y ago> what damage can that employee do in 5-10 minutes? This is not an authentication issue (JWTs) this is a classic authorization issue (Permissions/Roles). It's not the authentication layer's fault if you allow everyone root access. JWTs are just fine. Bearer tokens are just fine. You can write shitty session code just as easily as shitty OAuth2 code.
- ehutch79 4y agoYou're absolutely right, but then we reach the, "why are you using JWTs?" part of things. if you're issuing them for your own service because that's what some guy on reddit said you should be doing...
- ehutch79 4y agoTo clarify, what I do for sso stuff, if I get the JWT, verify it, then generate a session_id to hand back to the frontend. I'm essentially using the JWT as a replacement for username/password when it comes from a sso provider. I can then do invalidation or deny login as normal.
- jayd16 4y agoWhy doesn't the same argument apply when looking at other services? Can't they still do a lot of damage in that 5-10 minutes against those services?
- themenomen 4y agoCan't you keep a whitelist/blacklist of tokens in a memory cache like redis/memcached and go from there? As far as I know that is the standard practice to invalidate non expired sessions tokens.
- brunojppb 4y agoBut then you introduce a database-like dependency that potentially every micro service will need access to.
- themenomen 4y agoYes, that comes with its own caveats
- drinchev 4y agoAs explained in the article, if that's the case then you can't really trust the JWT anymore only for it's cryptographic signature and you rely on an internal store entry that makes the token valid / invalid. This makes no benefits as to bearer token or any random string that the server "knows" is a valid authenticated request via internal store, like a DB.
- eli 4y agowhy not just use a session token at that point?
- hunterb123 4y agoBecause you're only storing the invalidated tokens and you're only storing them for the length of the token's lifetime (expire the redis key when the JWT expires) So instead of storing all session tokens indefinitely, you only store invalidated tokens for a short period of time.
- ravenstine 4y agoSince when were session tokens ever a bottleneck? That's a problem I've never heard of on any scale. Yet again, JWT seems to be trying to solve a non-problem. Session tokens don't even have to be stored indefinitely. If a user isn't active for a period of time (even 30 days let's say) then the session token can be removed. Or, if memory truly was a problem for session tokens (not sure why honestly), transition tokens to storage after x amount of time and bring them back into memory when the user is active again.
- brunojppb 4y agoThis is interesting because one thing people ask me when a system is using JWT is in case they reset their password, how can they invalidate all existing sessions? They basically can’t. Using A cookie-based/token-based session strategy, you can do that quite easily.
- cogman10 4y agoJWT is a token, often stored as a cookie. I don't see how it's impossible to invalidate a JWT but easy to invalidate a cookie or token.
- Justin_K 4y agoIf you are using a cookie and managing the session expiration on the server, you can kill it anytime.
- cogman10 4y agoThrow a session ID in the JWT and do the same thing. JWT has a freeform payload that can literally be anything you want. Nothing about it prevents you from using a pattern like this.
- zaphar 4y agoIf you do this you get 0 value from using a JWT over a regular session id. It's simpler and likely less work to just not use a JWT in that case.
- cogman10 4y agoThe value add is you don't need a cryptographically secure session id generation mechanism when you work with JWTs. A simple session ID can be (and often was) forged to grant access to things end users shouldn't have. Put the session id in the JWT and now an attacker can't easily change the session they are associated with.
- pwinnski 4y ago> An old joke is that there are only two hard things in computer science: cache validation, and naming things. Way to ruin the joke! The joke is that that are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors. See, now it's a joke.
- bigDinosaur 4y agoMy go to version is: there are only two hard things in computer science: cache invalidation, naming things, and cache invalidation.
- eckesicle 4y agoand exactly once delivery, and exactly once delivery.
- gorkish 4y agoI'm sorry. I missed that. Can you please tell me again?
- MAGZine 4y agoit was in the original joke.
- remram 4y agoIf you add anything else, you ruin the "off-by-one" part.
- tmccrary55 4y agoThen there are three hard things
- pjmorris 4y agoI would tell you a UDP joke but you probably won't get it.
- 4y ago
- drinchev 4y agoWhat I'm pissed about is that everyone hopped on the JWT train too fast a couple of years ago. Now it's really hard to argue with architects / developers why cookie authentication / bearer token makes more sense than JWTs.
- ravenstine 4y agoJWTs aren't even hard to argue against in terms of logic. What is hard to argue against are developers whose theology includes JWT.
- cogman10 4y ago> Now it's really hard to argue with architects / developers why cookie authentication / bearer token makes more sense than JWTs. Because that's a nonsensical argument? JWT is just a token + validation. Nothing more. You can use JWTs in cookie authentication, you can use them as bearer tokens. The only thing JWTs are doing is carrying a payload and signing it. Now, if you want to talk about Oath2 or OIDC then maybe there's a different argument to be had.
- sbergot 4y agoWhy would anyone use a jwt in a cookie? A sensitive cookie should be encrypted. It does not require any signature.
- cogman10 4y agoI feel like this is mixing concepts. JWTs aren't for transmitting sensitive data or encrypting things. JWTs are about having claims that can't be forged by the client. So why would you put a JWT in a cookie? To give the end user a set of claims that they can't change, they can only read and give back to the server. Those claims can include things like user id, or session id, or whatever you might imagine. Now, could you accomplish the same thing with an encrypted cookie? Absolutely. I'm not arguing about what you can or can't do with stuff. But rather again commenters saying "JWT is such and such and forces so and so". It's nothing but a signed set of claims.
- wk_end 4y agoAs someone who's a little behind the times here, can someone explain the distinction between a session ID and a token? I'm referring to this passage: > Sessions were built on top of cookies. The server kept context about the user's "session" [...] and indexed it with a random session ID. The session ID was sent as a cookie and for each subsequent request, server looked up the session state. > Then came mobile apps and single-page JavaScript apps, and plain cookies and sessions started being inadequate. Developers started using tokens, where a token was an unguessable random string that behaved like an identity card. Possession of it proved your (client's) identity (bearer token). Both a session ID and a token are random strings clients send with requests to indicate who they are. Why were sessions inadequate, and how do tokens solve this problem?
- tyingq 4y agoI think they are trying to point out that a "session ID" is typically a key into session data stored on the server side, where the token is usually not just a key, but all the session data stored client side. With signing and other mitigations intended to keep that from being dangerous. >Why were sessions inadequate I suspect there are more reasons, but one is likely CORS and the tendency for the auth infra to be separate from the app infra.
- WA 4y agoSession ID: Server has a list of valid sessions. Compares your session ID to its own list. Have session token? Access granted. JWT: Server doesn't keep a list. Someone comes with a JWT, which is signed by the server. Server grants access purely on the fact that there is a signed token. JWTs are useful if you don't want to sync the server-side list of valid session ids (many microservices for example).
- deleted 4y ago[deleted]
- 0x457 4y agoThat's not entirely true. Session cookie doesn't have to be opaque and can be signed and encrypted. That's how RoR been using it for long time. Realistically, you only need to make sure that an unexpired and verified session hasn't been revoked. Opaque sessions are smaller, though.
- bjt2n3904 4y agoI was significantly creeped out that my state was issuing COVID passports with JWT. Especially when I signed the opt out form requesting to not be placed on the database. Especially 2.0, when I called the database, and was told that my records could not be deleted.
- misnome 4y agoHow is issuing a JWT implicitly mean that they are storing it in a database? Couldn't they have just... not stored the data... but can still validate it?
- infamousjoeg 4y agoExactly this. They just need to validate the JWT signature against a JSON Web Key Set (JWKS). There's no need to store the data.
- tylergetsay 4y agoThey used "JWTs" as a convience, Smart Health Cards have none of the issues here. Their issuance doesnt require a database either, thats just your healthcare provider.
- adolph 4y agoJWT and SMART Health Cards are similar under the hood. The T part of JWT refers to a Token, which in JWT is a standardized set of claims. Instead of T, SMART Health Cards use S, or Serialization. Instead of a token, the JWS serializes FHIR demographic and necessary medical information about the card bearer. SHC has all the same invalidation and key issue/revoke challenges as JWT. When the issuer is ready to generate a Health Card, the issuer creates a FHIR payload and packs it into a corresponding Health Card VC (or Health Card Set). The VC structure (scaffold) is shown in the following example. The Health Cards framework serializes VCs using the compact JWS serialization, where the payload is a compressed set of JWT claims (see Appendix 3 of RFC7515 for an example using ECDSA P-256 SHA-256, as required by this specification). Specific encoding choices ensure compatibility with standard JWT claims, as described at https://www.w3.org/TR/vc-data-model/#jwt-encoding https://www.w3.org/TR/vc-data-model/#jwt-encoding. https://spec.smarthealth.cards/ https://spec.smarthealth.cards/
- newbieuser 4y agowhy is a blog post that directly praises its own product for short reasons on the homepage?
- brunick 4y agowhy is this not the top comment...
- eagsalazar2 4y agoBecause the content is also interesting, provocative, and 100% correct. Why are you attacking the character of the witness instead of the substance of the testimony?
- eagsalazar2 4y agoHallelujah! I've been saying this for years and people looked at me like I was insane. JWTs are one of the biggest cult/hipster scams of the last few years. GraphQL everywhere is another one (like JWTs, it has its uses but people went way overboard) and Tailwind is the next one.
- xtracto 4y agoI see a lot of the comments in this thread from people that apparently just do not get the problem with JWTs. I was using "presigned access/bearer tokens" way before JWT was a thing. There's multiple safe and easy ways to do authentication/authorization without providing a signed green card to the client which you don't have the ability to cancel at any time. As long as you keep control in a database.
- elforce002 4y agoWhat's wrong with tailwind? It made css styling accesible and easy at least for me.
- justusw 4y agoI agree, Tailwind seems to be out of scope here for comparison. One is about server architecture, the other one is about how to write CSS. Both have a completely different impact (JWT as a footgun vs. Tailwind improving/worsening developer comfort)
- hbrn 4y agoMicroservices and Serverless are another two. IMO the only hyped up piece of tech that was actually good in the last decade is containers (but not the orchestration, just containers).
- eagsalazar2 4y agoServerless? Huh I can't get onboard with that one.
- 4y ago
- wdb 4y agoCookies are quite problematic these days
- red_trumpet 4y agoCare to elaborate on that?
- eagsalazar2 4y agoProbably means "socially problematic" because there is real orthodoxy here. If you speak badly JWTs in an interview... that's probably problematic.
- wdb 4y agoIf people have cookies disabled, or when you try to load content in a semi-sandboxed manner by using IFRAMEs than you can't use cookies, localStorage, sessionStorage etc.
- marcosdumay 4y agoYou mean first-party session cookies disabled? How many people do that? Or better, how many people do that and still expect anything to work? (Anyway, iframes don't break those in any way.)
- quesera 4y agoI have happily used JWTs as signed objects that can be easily parsed and validated by any API consumer, in any language, using library code. These objects can be transferred through untrusted channels, and retain their verifiability. That can be useful when moving data between organizations, or systems that do not talk directly (e.g. a mobile app that interacts with multiple unrelated backends). RFC 7519 says: JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. Not all claims are authorization claims. Not all claims require ad hoc invalidation. Some claims can even be permanent! Authors ad infinitum have pointed out the risks in using JWTs for authorization (linked web article says "authentication", but both could apply). Those risks are: - Invalidation/expiration controls are limited - Receiver might not properly validate signature - Protocol dumbly allows "none" algorithm Only the first is an operational concern, the others are just "bad code works badly" problems. The moral of the story is: If your claims do not fit the timed-expiration model of JWTs (e.g. some authorization claims), then don't use JWTs!
- marcosdumay 4y ago> the others are just "bad code works badly" problems Software should be hard to misuse. If you have a library intended for universal usage, and the library users have to remember to add some code every time they call it, then it's a bad library. If you have an specification intended for universal usage, and the implementers have to remember to always do 3 operations together, than it's a bad specification.
- kreetx 4y agoRight, but rm -fr / is also easy to write, but is pretty bad code. JWTs and statelessness have their uses, building in refreshing is not that difficult (if it's not built in already), and using "none" well, just don't use that.
- marcosdumay 4y agoThere are alternatives that won't accept "none" or broken encryption algorithms, and that won't allow you to access the token data without verifying its authenticity. JWT is just a bad standard all around.
- Ocha 4y agoI think this article is shortsighted: what about not needing to store token at all? I think that is one of the biggest strength to it - you can issue short lived tokens in high volume without needing to store anything anywhere.
- Salgat 4y agoThe only argument they elaborate on is still easily addressed with a validation of the token against a database on every request, and it's hardly a drawback compared to other methods if the other methods do the same thing.
- fknorangesite 4y agoWell, it's a drawback because if you're doing the validation anyway, why bother with the added complexity of the JWT in the first place? You've removed the primary advantage.
- Salgat 4y agoI'm not sure why JWTs are considered complex. In C# I generate tokens with a couple lines of code. Sure you can get fancy with the claims, but it's not required if you're going to access the DB anyways on authenticated requests.
- fknorangesite 4y agoYou're right, they aren't, particularly. Just moreso than alternatives - especially if > it's not required if you're going to access the DB anyways on authenticated requests. then what's the point? You're just re-inventing bearer tokens.
- Salgat 4y agoI can see one massive advantage is that you could disable the db access/verification for service-to-service communication, since revoking an internal service token is exceptionally rare (and if it occurs, you have much bigger problems to worry about).
- fknorangesite 4y agoWhich is exactly the kind of valid use case already presented in OP.
- weinzierl 4y agoApart from the issue of not being able to log out there is the following list in the article: "We've ignored things like increased attack surface due to complexity of JSON parsing/validation, misconfiguring JWT libraries to allow no signature, leaking data to users because you thought JWTs were encrypted (they're usually not by default), and poor implementation of API clients that don't properly re-run requests that failed due to expired JWTs. The list goes on, and on, and on ..." All of these sound like usability issues. Not to downplay them but are there more serious issues with JWTs?
- pionar 4y agoIt's like C. The language is fine, it just allows you to do bad things too easily. The same is true with JWTs. The idea is fine, but allows you to do bad things too easily. The no signature bit was a huge flaw in almost all JWT libraries across languages a few years ago. There are better schemes out there.
- oautholaf 4y agoIn my experience, a working strategy for handling signout or revocation for statically verifyable tokens like JWT is straightforward: - Clear client side state where you can. - Write signed out/expired tokens to something with a cheap heavy read/eventual consistency model - Fail to signed in if unavailable - Acknowledge that you are gaining latency/availability/ lower costs by trading some precision I am aware of a very large website most folks use every day that did this for more than a decade and it worked fine.
- jdthedisciple 4y agogreat idea! I'm using JWT in one of my projects and still unsure how to fix the irrevocability of JWT while keeping them stateless. But this seems like a nice intermediate solution
- gumby 4y agoThankfully, recent events have changed the expansion of JWT in my brain's cache: when I first read this I thought "James Webb Telescope". Not being a fan of JWT authentication I was doubly relieved when I clicked through.
- caeril 4y agoThis is a good overview, but I have yet to hear a compelling reason to use JWT. String session tokens generated by a CSPRNG and stored in a cookie work fine for every use-case I can think of. What specifically is the argument for JWTs?
- dzikimarian 4y agoWe have single SPA as front for multiple backend apps (I wouldn't call them micro services - each is responsible for pretty big part of the business and maintained by separate team). There's single identity provider responsible for token generation, sign in, refreshing the token every few minutes. It's easier to have for eg. userId embedded inside signed token. Nobody has to call identity provider, they don't even care from where did the tokens came from. Our threat model for this software doesn't care too much if token is valid for some seconds after logout. At this point user was probably MITMed or lost control over hardware and has much bigger issues than us. Could we do this differently? Probably yes. Would there be a positive impact for the company if we dedicated time to this? Very doubtful. JWT is only a tool. Sometimes it fits, sometimes not. No reason to get religious over this.
- vivekv 4y agoI don't quite understand the need for access and session token as a mechanism of expiring sessions. Can we create a signed JWT with the expiration in the body itself? Since it is signed the expiry cannot be tampered with.
- Benlights 4y agoIf there is an expiration in the JWT, logging off is still an issue. You can't log out until the JWT expires.
- sascha_sl 4y agoIf you mean access and refresh tokens - both usually have a lifetime in the signed payload. Your access/ID token is short-lived (~5 minutes). This token is trusted without confirming if the user still has access. Your refresh token has a longer lifetime (hours to months) and can be used to trade for another access token (and a new refresh token, invalidating the old one), but every time you do this trade your authentication server can also check if the user still exists, is not banned, has not signed out and still has the same claims (username, email, groups...) and either not issue a new token or a token with different claims. There are proxy servers that will do this entire thing in the background for you and hand you the claims of the current access token in HTTP headers.
- sascha_sl 4y ago>Issue solved, right? Well, kind of, except you've just reintroduced a bearer token, because that's exactly what the refresh token is. Entirely missed the point that refresh tokens will not work when your app (or your user) has told the IdP to sign out - unless you requested offline access.
- datavirtue 4y agoHmmm...put the expiration datetime in the token and have your middleware handle it (verify and check for expiration)? Failing to see a problem.
- jdthedisciple 4y agoThat's already done. The problem is that apart from expiration, the token is never invalidated, for example when the user logs out. An attacker who stole the JWT is still logged into the victim's account until expiration.
- nfw2 4y agoNot super-opinionated on this, but let me try to steelman the JWT case. Yes, to perform session invalidation with JWT requires some amount of centralized state, so a perfectly-decentralized auth system is not actually possible. However, using JWT means this centralized state is much less heavy than traditional sessions. Instead of saving ALL sessions and ALL session data on the server, JWT only requires saving a small fraction of session ids (those that have been recently invalidated) and NO session data. By using JWT, you have simplified your memory needs and reduced them by multiple orders of magnitude.
- kerblang 4y agoThe JWT is irrevocable by design, which is why it's time-boxed to a few minutes and not a few days. The refresh token is meant to be revocable. You the provider would store that in a database and remove it or mark it invalid when you need to shut the user out. So no, it is not simply moving the original problem around without solving it. Most software devs using cookies would likely struggle to revoke an individual cookie - you can certainly architect that in, but if you're like most of us, nobody thought about it early on and now it's kinda problematic to retrofit. Same reasoning: "Well, it will expire on its own soon enough." JWT's actually make it easier to guarantee expiration since it's part of the token itself instead of being reliant on server-side mechanisms. It's definitely a pain in the butt to juggle refresh tokens & access tokens as a client-side dev, and almost everyone's API docs are ambiguous and confusing about token lifetimes (refresh tokens often have lifetimes too). But that's another issue.
- P5fRxh5kUvp2th 4y agorefresh tokens are a workaround for a problem that wouldn't exist if you chose not to use a JWT.
- kerblang 4y agoAgain: If we decide to use cookies instead, we also need to architect in a Cookie Revoker to fix the same problem: That means tracking cookies against user accounts on the server side. I'm sure some folks have done this, but I don't know of any common frameworks that actually support it.
- P5fRxh5kUvp2th 4y agoOr you can develop like it's 1999 and simply remove the session from lookup.
- matt74827289 4y agoI just use both. Use randomly generated tokens that you use to look up user information in your database, but also sign that token and present it as a JWT.
- 0x457 4y agoI think the only two ways to use JWT tokens is: 1) you have some kind of api gateway, it would validate the session, issue JWT/PASETO that lives a minute or so, downstream services would use that token to talk to complete the request. 2) When you need something like AWS S3 presigned URL. Everything else is just an opaque session token with extra steps.
- jdthedisciple 4y agoLack of invalidation ("out of the box") is indeed a weakness of JWT. However, I think in some scenarios it doesn't matter. For example if all the user data is encrypted, an attacker can retrieve it from the server using the JWT but not decrypt it - how useless! Besides, when it comes to criticisms like this, I would gladly like to be pointed to real-life incidents where JWT as the security-bottleneck was fatally exploited.
- anonymous344 4y agoGreat article. I was going to start finally using jwt:s but this helps me not to. Currently using sessions (fast & easy) and if not found, then cookie&db-login. Just after migrating the server found out that saving the sessions manually to database was great. That allowed all users to stay logged in while the server changed.
- highhedgehog 4y agoAs an exercise I started experimenting with JWT after a colleague told me how great they were. So i tried to build a simple CRUD webside with authentication using JWT just to practice. The section "Problems with JWT" perfectly explains the issues I had. I think a way too many people just pick up the next random fad and without thinking they start using it.
- chrisshroba 4y agoIt seems like most of the commenters here are blindly choosing a side when the real answer is, it depends on your priorities. If you want statelessness and one fewer db calls at the expense of timely revocations, pick JWT’s. If you want instant revocation, then accept that you need to check a database every time and don’t use JWT’s. Both options are correct. As an aside, if you do pick JWT’s, you could create a revocation queue, publish all revocations to that queue, and read that queue asynchronously in every server to keep a token blocklist. You lose statelessness but retain speed (no db call).