8 ms·
Understand JWT in 3 Minutes
- rvz 7y ago> Q: If I tried to use this token after 10 years, would it still work? > A: Yes, it will be valid forever unless the server specifies an expiration time when generating it. The implications of this is beyond calamitous. This is why Disney+ and Fortnite logins were hijacked in the first place. I can harvest all these JWT logins with a good chance of people forgetting to ever logout. Hence this, with one push of a button I can abuse an API endpoint to mass delete everybody or what not. Best part about JWTs? They are unencrypted by default. For that reason, Just do not use JWTs.
- cheez 7y agoThe server can invalidate the token at any time.
- arethuza 7y agoTo do that you need to store some information about the token centrally so that any server receiving the token can check to see if it is valid or not - and if you are going to do that why not use an opaque random token and store all of the data that would have been in the JWT in the store?
- tehbeard 7y agoStoring a dozen bytes of 5,000 expired token ids until they expire vs several hundred bytes of 100,000 sessions. Granted, its use case leans towards big systems, or systems that cross boundaries between orgs.
- zxcmx 7y agoNot the OP, but I guess the TL;DR for me is that it's usually ok for sessions to be loosely consistent, and you can upgrade to "hard" consistency where you need to. Enforced session state consistency creates a hard runtime dependency on the backend service that provides that data and that service needs to scale to handle every single client request with low latency because the token to session state lookup dictates a floor on the response time of every other service you can possibly provide. It's not "wrong", of course lots of systems work like this, it has some advantages! It's just a tight runtime coupling that constrains how you can scale in some ways. The way I think about it is, if you have jwts you can always add additional "hard consistent" session state in the way you describe, but you're not forced to use it for everything. You have options, you can make tradeoffs. And in engineering, room to make tradeoffs is a great thing to have. As an example, with basic jwt sessions you can write say, a non-sensitive geodata lookup service for frontend (don't really care if user session is "valid" for an extra minute after "logout") in a lambda say, scale it to bejesus, but still be able to attribute requests to a user and do rate-limiting, and it has no availability dependencies on anything else. Ok sure though, maybe change profile info (a low volume request), you need to eat a hard invalidation lookup.
- cheez 7y agoCould you encrypt the JWT content with user-specific keys and cycle those keys in case of an issue?
- api 7y agoWhat else should we use that is not over-engineered?
- rvz 7y agoHonestly, I find that PASETO [0] is a better candidate to replace JWTs since it supports encrypting these tokens and doesn't have multiple ciphers to choose from, unlike JWTs. They can be used just like them for signing, etc just without the weak cryptography in the token. Fernet [1] was close to being an alternative but I've seen that even Branca [2] tokens look much more like a saner alternative for replacing JWTs. [0] - https://paseto.io https://paseto.io [1] - https://github.com/fernet/spec https://github.com/fernet/spec [2] - https://branca.io https://branca.io
- kam 7y agoFor sessions? A random token and a key-value store.
- moltar 7y agoCookies have been battle tested and are very secure. Enable http only mode and you can’t even access them from JS thus eliminate possibility of take over / token theft.
- Freak_NL 7y agoJWT's generally are not used without setting the expiration date, just like you wouldn't have a server-side session continue forever as long as the user presents their session cookie.
- hangonhn 7y agoI think the problem is that you need to either make the JWT have a short expiration or engineer a way to invalidate them before the expiration if the need to do arises. From what I can tell most people implement a blacklist of invalid tokens that need to be expired early. This isn't exactly the same as a traditional sessions table since it turns the problem on its head. You're likely to have a lower number of early expired JWTs than valid sessions. The other way you might be able to solve this is to generate a per-user JWT key and use that to sign the JWT or embed that in the JWT. When you need to force a log out, just regenerate that value for that user.
- leddt 7y agoIn our app the JWTs have a 5m lifetime. When a JWT is generated we also generate a single-use refresh token. When a client tries to use an expired JWT the request fails, and the client will then exchange the refresh token for a new JWT/refresh token pair, and finally retry the request with the new token. The refresh operation can reject the request if the user has been deactivated (it's basically a new login request, using the expired JWT as the username and the single-use token as the password).
- multiplegeorges 7y agoPerhaps I'm misunderstanding, but how does this help in the case of a compromised token? Doesn't this assume the attacker hasn't also compromised the refresh token? Presumably, the token and refresh token are both stored in the client-side app. If that gets compromised, the attacker now has the username/password combo they need to restore the session after the T+5mins has expired.
- 7y ago
- KukicAdnan 7y agoSo because someone gives bad advice or has a bad understanding on a technology, you should not use it? Seems a little dramatic, don't you think? JWTs, like most things, work perfectly fine if implemented properly and you understand what you're doing.
- ianleeclark 7y agoAlternatively you could just use a token that has sane defaults, rather than having a tool that could bite you or could bite your organization after you depart.
- KukicAdnan 7y agoI've implemented JWT's in apps more times than I'd like to think about, and never has it been done without ensuring the tokens are signed, signing keys rotated regularly, tokens having a short lifecycle, etc. and none of these required some deep expert knowledge just a couple of hours of research on best practices. Again, it's not about the tool, it's how you use it.
- ergothus 7y ago> This is why Disney+ and Fortnite logins were hijacked in the first place Citation? I'm in total agreement with the problem of unexpiring tokens, but last I heard the suspected culprit in Disney+ was credential re-use. If there's newer info, I'd love to get a pointer to it. > For that reason, Just do not use JWTs. That seems a bit sweeping. You can apply the "unencrypted by default" dilemma to just about everything. Noting that you have to take an extra step doesn't invalidate the entire concept.
- emsy 7y agoOr just understand the technology you are using and the use case for it. PS.: You clearly did not understand JWTs.
- rumanator 7y ago> Best part about JWTs? Just to be clear, JWT do support expiration time and nonces. For implementations to be vulnerable, they need to intentionally avoid standard security practices. The tool isn't the one to blame.
- falcolas 7y agoSo, not only do you have to ensure that your use of JWTs is sane, you have to ensure that the library you're using is doing sane things (by default, or by configuration)? The right thing to do should be the easy thing to do. There's little "easy" about the "proper" use of JWT.
- rumanator 7y ago> So, not only do you have to ensure that your use of JWTs is sane You're the one using JWT. You can't blame the tech if you screw up how you apply it. > you have to ensure that the library you're using is doing sane things Isn't this concern observed in 100% of cases where a third-party lib is used? > The right thing to do should be the easy thing to do. There's little "easy" about the "proper" use of JWT. That is not true at all. It's quite simple: either you know what you are doing or you develop broken software with security problems. If you decide to adopt a security technique and then fail to learn the very basics then the tech is not to blame for the problems you create for yourself.
- FisDugthop 7y agoThis is the Irrevocability Myth from "Capability Myths Demolished" [0], a classic article explaining why JWT-style fusion of authentication and authorization is not unsafe. [0] http://srl.cs.jhu.edu/pubs/SRL2003-02.pdf http://srl.cs.jhu.edu/pubs/SRL2003-02.pdf
- stedaniels 7y agoWhy not to use JWT in 3 Minutes: http://cryto.net/~joepie91/blog/2016/06/19/stop-using-jwt-for-sessions-part-2-why-your-solution-doesnt-work/ http://cryto.net/~joepie91/blog/2016/06/19/stop-using-jwt-fo...
- pat2man 7y agoThat only describes why you shouldn't use them for sessions, not why you should not use them at all.
- thinkloop 7y agoWhat is there besides sessions?
- grenoire 7y agoAPI access?
- joepie91_ 7y agoFor API access, there's no point using JWTs either. In the vast majority of cases, a randomly-generated API key is sufficient and JWT would be unnecessary complexity (you're using TLS, right...?) and in the odd high-security usecase where the key still must not ever be sent to the server, you can use eg. client certificates. And if for some reason you have a weird freak edgecase where you really do need a cryptographically signed stateless token... JWT is unsafe[1] and you want PASETO[2] instead. [1] https://paragonie.com/blog/2017/03/jwt-json-web-tokens-is-bad-standard-that-everyone-should-avoid https://paragonie.com/blog/2017/03/jwt-json-web-tokens-is-ba... [2] https://paseto.io/ https://paseto.io/ Edit: To be clear, with "API" I'm assuming you mean "third-party API", in the original sense of the word. If you just mean "a bunch of endpoints for my SPA", then you should use none of these things, and just use sessions. It's not really an "API" in the "API key" sense.
- staticassertion 7y agoThe article addresses the singular valid use case at the bottom.
- azhenley 7y agoThe post never tells you what JWT even stands for. I thought it was the Java Web Toolkit...
- moltar 7y agoI’m still not understanding the advantages of JWT over cookies for user facing auth. I do see use cases for JWT for machine-to-machine auth though.
- kyriakos 7y agotechnically you keep some session data on the client which would normally be kept on the server
- matthoiland 7y agoA server can issue a JWT and forget about it. Most cookie auth strategies requires the server to persist the token to confirm validity. Also, a JWT can work across a microservice architecture easily for the same reasons.
- latortuga 7y agoThe biggest problem with JWT is there is no revocation mechanism which IMHO is a non-starter. Introducing revocation mechanisms generally means introducing central state and now you're back to why not just use a session token? Not to mention the numerous issues JWT has had over the years.
- sam_lowry_ 7y agoFinally a meaningful explanation of JWT.
- latortuga 7y agoThe correct comparison is JWT vs sessions, not JWT vs cookies. Cookies are a storage mechanism, and you would compare them to localStorage. Assuming you meant JWT vs sessions, yes, there aren't any except that it's super trendy.
- shantly 7y agoThey let you answer the question "did some other machine I trust find this entity to be a valid user, having this identity and the rights they assert they have?" without asking that machine directly or storing anything about the user. More or less. Provided the keys haven't leaked, of course. The chief difficulty this introduces is manually invalidating tokens. You end up having to store some data and/or ask some other system questions about users (blacklist-related, in either case) after all, reducing the initial benefit. But distributed sessions will run into similar problems anyway. Basically if your auth lives the same place as all parts of your application the user will ever see, don't bother with it because the benefit is little to none, otherwise, JWT's a solid maybe.
- brimtown 7y ago> Q: If I have to include this token with every request, where should I store it? > A: Typically, you would store it in the localStorage, after the user logs in and gets the token. This seems to contradict Auth0's guidance to not store tokens in localStorage since it's vulnerable to XSS: https://auth0.com/docs/security/store-tokens#don-t-store-tokens-in-local-storage https://auth0.com/docs/security/store-tokens#don-t-store-tok...
- rumanator 7y agoThanks for the insight! If anyone cares to provide any clue about best practices and how to handle token storage, you are more than welcomed to provide any insight.
- KukicAdnan 7y agoHere you go: https://auth0.com/docs/security/store-tokens https://auth0.com/docs/security/store-tokens Gives various suggestions depending on your use case.
- moogly 7y agoI've been looking at this for months without getting a clear, noncontroversial answer. Even with this documentation, it is still unclear what to do if you have a SPA on another host than your backend (so you can't use cookies), and you do not want to use server sessions. Using `oidc-client` from the frontend could work, but that bundle size[0] is absolutely insane. [0]: https://bundlephobia.com/result?p=oidc-client@1.9.1 https://bundlephobia.com/result?p=oidc-client@1.9.1
- thdrdt 7y agoYes, but when the server does not send the token as cookie the only option is to store it with JavaScript. And yes, that also means (any) JavaScript can access the token.
- dantheman 7y agoI can't believe it doesn't even define what JWT means... JSON Web Tokens
- matthoiland 7y agoI can't believe it doesn't even define what JSON means... JavaScript Object Notation
- mettamage 7y agoAnd yet he didn't explain how JWT differs from session cookies. I suppose I'll never learn. (looks hopefully at the HN crowd)
- pat2man 7y agoFrom my perspective, it is a session cookie + some other verifiable attributes. For instance if you are using OAuth you can include the OAuth client ID in the JWT. Now you don't need to look it up each time.
- vinceguidry 7y agoCookies have a special storage place in the browser and limited storage space. This limitation makes it so that usual practice for cookies is to store only a UUID-style identifier client-side and the rest of the data for the session server-side, necessitating a database round-trip before you can even know who's hitting your server. JWT allows you to use the browser as the fatter client that it has been slowly growing into. Because JWT is JSON, it can store anything, and you're only limited by how large you want to make your web requests. (they're sent with each request) At the end of the day, they're both ways to build state into a stateless protocol.
- shantly 7y agoJWT is just some arbitrary JSON data, with a few customary fields, cryptographically signed by whichever system issued it. You send it to the client, which may be a browser or mobile app or whatever, and they send it with each request to any related systems. A system receiving a JWT can verify that the stuff in it was certified as true or accurate by the issuing system, given only the correct keys to check the signature and no further info about the user. One might, for example, put user identity info & user roles (for permissions) in a JWT. This can be useful for e.g. checking login status at proxy or cache servers without having them connect to a database or ask other systems (so, works very fast), for microservice bullshit, or for systems with lots of access points and unified login (think Google, with Youtube, Gmail, Docs, and so on—I don't think they use them, but that's the sort of situation in which one might) The main downside is that you can do stupid crap with them like not set an expiration, and you can't really expire tokens prematurely (say, on user role changes or on user deletion) without re-introducing some centralization. Neither are crippling but they do make it less the magic bullet than one might hope.
- ajbeach22 7y agoI've seen lots of tutorials for single page apps/api architectures that specifically store JWT in localstorage, it's endemic. What I haven't seen though, is guidance on how to deploy SPA web apps using cookies properly (with either jwt or session token in http only cookies) From what I have found, there are only a few options: 1. host api at 'api.mydomain.com' and frontend from 'mydomain.com'. You will have to deal with CORS and options requests which can add significant latency for non-simple CORS requests. Not to mention extra configuration with CORS headers. 2. Serve assets/frontend from the API (ie, rails static assets, Django collect static, etc). Downside is that you have to deploy everything together. 3. Reverse proxy so that api/frontend are on the same domain, and you can use cookies without CORS. Api lives at 'mydomain.com/api' and frontend at 'mydomain.com` I am currently doing 3, which if you are using AWS, you can use CloudFront as the reverse proxy by using a separate dristriburion for your api and your Frontend and using behaviors to route traffic by path. In fact, that is what AWS recommends: https://aws.amazon.com/blogs/networking-and-content-delivery/dynamic-whole-site-delivery-with-amazon-cloudfront/ https://aws.amazon.com/blogs/networking-and-content-delivery... So for 3, for example: You have CloudFront -> Loadbalancer -> EC2 for your api with a path of /api in CloudFront, you can set CloudFront to never cache. You don't pay for bandwidth between EC2 -> CloudFront, you only pay for bandwidth out of CloudFront: >Outbound data transfer charges from AWS services to CloudFront is $0/GB. The cost coming out of CloudFront is typically half a cent less per GB than data transfer for the same tier and Region For your frontend, you can host in s3 -> CloudFront with a catch all path for non-api paths (allows client side push state to work in SPA). CloudFront in this case also is where SSL termination happens. You can also to full end to end ssl if you enable that in the CloudFront and your API can also terminate ssl at the LoadBalancer. The other benefits to this approach is that you can usually just use the default auth systems for your web apps. You can also create a CNAME for your API loadbalancer to be api.mydomain.com and use that for non-web clients. In the case of Django Rest Framework, there is both cookie and token auth enabled by default.
- falcolas 7y agoOne thing missing: the "cryptographic signature" isn't required to be a cryptographic signature by the standard. You need to ensure, by configuration or by library defaults, that the algorithm of 'none' is not allowed, otherwise someone could freely modify and replay the JWT for all time. https://tools.ietf.org/html/rfc7519#section-6.1 https://tools.ietf.org/html/rfc7519#section-6.1