There are just too many ways to do JWT wrong. 😢
And I fell for some... Don't panic, but it's likely to be your case as well.
Check thes...
For further actions, you may consider blocking this person and/or reporting abuse
The problems with JSON Web Tokens are that it's an error-prone cryptographic design.
Most of (if not all of) the work you had to do to get JWT security flaws fixed should never have been necessary in the first place. Furthermore, there may still be as-of-yet undiscovered flaws in the JOSE standards since they do a lot of things that maximize the risk of implementation error.
You're better off implementing something less foot-bullety. I wrote PASETO to replace JWT. Maybe a good starting point?
Hey Scott, thanks for joining the discussion!
I very welcome this suggestion. Definitely am open to new implementations that would excel current ones, in any area. 👐
Never heard of PASETO until now. I read very quickly, but I promise I'll give proper time to familiarize myself as soon as I can. Maybe we can contribute on DEV with article about it? Let me know how the idea sounds to you.
At first glance, what I captured is:
Did I miss any important top-level aspect of it?
A few considerations came to my mind in order to validate the true value brought by the PASETO implementation.
Not questioning the value at this point. Sort of a peer reviewing in search for practical confirmation.
My rule - I trust it's a fair one - is: always confirm by experience before accepting something as truth. 😉
I'll get back to you when I find myself ready for a productive and intelligent discussion on the topic! 👍
You mostly got the idea right.
The design of PASETO was influenced by a simple observation about real world cryptanalysis.
Let's say you were tasked with building a brick wall. Would you...
Which design would you trust to hold up a roof?
Option 2 is what the JOSE standards (JWT, JWE, JWS) do. Option 1 is what PASETO does. PASETO doesn't merely hide the algorithms, it forces developers to one of two modes that have security turned up to 11, based on their specific requirements.
PASETO's design was inspired by the least controversial meta-observation in cryptography today: Cryptography vulnerabilities more often lie in the metaphorical mortar rather than the bricks.
Randal Degges gave a talk about PASETO recently. The slides are available here.
Looks good, thanks for clarifying. Will research more into it.
Hey Scott, it's been a long while, but I finally managed to get a bit more familiar with PASETO. Thought I could pick your brain to understand a bit more about the feasibility of the concept.
I've read this thread on IETF discussing the feasibility of adopting PASETO as a replacement for JWTs. From what I could understand, at that moment (2018), the overwhelming majority of experts in that group didn't find it a good idea to adopt PASETO as a replacement.
They seemed to value a few ideas from PASETO that could be incorporated in a new, stronger version for the JWT specification, while other parts of the PASETO specs did raise security concerns.
What is the current thought among the community experts with regards to this? Is PASETO at the point of adoption as an industry-standard?
Hi, I think you built your
localstorage
critique on a wrong claim:"Problem is: any JavaScript code in your frontend is able to access the JWT. And do whatever it wants."
The
localstorage
is isolated from other domains and only accessbile to scripts from the same domain. Those can manipulate thelocalstorage
, as they can manipulate cookies from the same domain.Cookies on the other hand can be used for CSRF attacks if CORS headers are not set correctly (see: stackoverflow.com/a/37635977/1337474 ). They do have advantages though - you can set expiration/max-age times and they are sent also with links where you possibly cannot set
Authorization
headers like with file downloads.Hi Johannes, those are very important concerns! I'm glad you raised them in this discussion!
You are absolutely right that other domains wouldn't be able to access your
localStorage
implementation. Nonetheless, this would be possible in case of an XSS attack to your site. This was the scenario I pointed out in the article:CSRF is indeed a real threat to cookies. That's why I suggested setting them with the
sameSite
property:This protects your JWT against some CSRF attack vectors, but not your entire implementation. There are additional measures you should take, such as:
Keeping JWT token in localStorage is fine. The only concern is XSS which should be avoided at all cost.
Once your site is vulnerable to XSS you got more bigger problem rather than just stealing JWT token.
So store the JWT token in localStorage and make sure your website is battle tested against XSS.
It can be "ok" and acceptable in some cases, but definitely not the best practice from a security standpoint.
A good analogy here would be our house. We need to secure doors and windows against unauthorized access. If a malicious actor gets in, we've got big problems, yes. But that doesn't mean we shouldn't hide our valuables. We may still store jewelry, money and other values in a safe. That practice can mitigate the losses in case someone breaks in the house.
Awesome post, I have been looking into authentication like this and this answered most of the pending questions I had around how to keep it secure. Some other resources that I have looked at were vague on this.
I had a question on this:
Would it just use the Set-Cookie Response Header or is there a different method?
Thanks!
Hey, Ryan! Thank you for the kind words, I'm glad to have added some value!
That's the HTTP standard to set the cookie on the response request. It's likely that your backend has a wrapper for this - as in nodejs. This way we don't have to worry about HTTP standards, use a more friendly API instead.
Some suggest sending the JWT in the Authorization header:
This helps to prevent CSRF attacks but is exposed to frontend JS. Using the SameSite in your cookie will help against CSRF anyway.
In case you're worried, use both. You can have your main JWT set as a cookie, and a second JWT set in the
Authorization
header (may even use a different secret). The second one doesn't even have to contain the same info, perhaps only the user ID.Then your backend can decode and validate both on each request. Doesn't add too much overhead and comes with an extra security layer. 😉
That makes sense, thank you!
What about a microservice architecture, where one service may handle authentication and issuing tokens, but those tokens can then be used to authenticate to other services? If you use a cookie to store the token in this case, you can't rely on the browser forwarding it to other services due to privacy settings. 🤔
That's a good question!
What I would do is:
That's actually the same thing if the JWT was coming as a header or in the request body payload. The public endpoint would need to extract and pass around to internal services anyway...
Does that make sense? 😉
So you're suggesting to have a single public service which proxies requests to other backend services? This is actually how we have just implemented this at my work. 🙂
However, my question was how you would approach it if you had multiple services your frontend could communicate with directly. One of the advantages of JWT is that any service with access to the signing secret can verify the token and trust the claims within. So, in theory, if an auth service issues the token to the frontend, then another service can receive and decode the token without involving the auth service again. But how can we secure the token on the frontend in this case?
In that case, I can see two options:
¹ Some architectures have resources to mitigate that. The JWT decoding could be implemented as a Layer, if you're using AWS Lambda, for example.
Hi! Nice article!
Regarding #2, you're assuming that it's a browser on the client side (so that you can use a cookie). In the case of a mobile app, what would be a secure alternative not to have the token on the response body? Use a HTTP response header?
Regards!
Hey Alexandre, thanks for stopping by!
That's correct, the advice assumes the client is a web browser.
I don't have experience with native mobile apps at all. But I found potentially useful references:
Again. Not my area of expertise. These are just what seemed to be relevant to me from a quick web search. Use with caution! 😉
(saudações de Minas, Brasil! 😄)
This type of advice will sadly not help the reader. Here's why:
Hi Sandrino, thanks for taking the time to contribute to the discussion!
The whole point of the discussion is when we have a backend securely authenticating a user. JWT won't apply to Frontend-only scenarios.
A large portion of web apps nowadays have a backend, so I wouldn't agree that the discussion here is useless...
About your second topic, it's a discussion beyond the purpose of my article. It's fair for you to prefer using Session IDs, but many people have a different view.
On whether JWT is a good authentication solution or not. I'm going to need to differ on this statement:
First, sessions are just cookies, they're no different. Storing a Session ID or a JWT as a cookie in the browser is essentially the same thing.
The advantage of a JWT is that, once the backend receives it in the request header as a cookie, it doesn't need to go anyplace get more info. It's self-contained.
This is a property called
stateless
and it plays very well in distributed environments designed for variable demand and smoother scalability.Whereas with a Session ID, the backend still needs to ask a storage engine to authenticate who is the owner of that session. It's a design that is more difficult to scale.
I'm not referring to frontend only scenarios, there is indeed no such thing as frontend/client-side authentication. What I'm referring to is modern applications where the frontend is hosted on a static file server and the backend is an API often running on a different (sub)domain.
An application could be running on AWS S3 on acme.com which then needs to call an API (eg: Heroku) an api.acme.com. In that case a JWT can be used to serve as a bearer token, but the site running on acme.com has no backend which can set cookies. A backend and an API can be the same or different concepts.
I'm not talking about Session IDs, I'm talking about sessions. Session use cookies and they can contain a session ID where a backend data store is used or they can be self contained, where the data is stored in a cookie and then encrypted.
express-sessions
is a good example of this.Sessions in every platform already have all the required tools to make them work for many different use cases:
It's not:
We're getting way way beyond the purpose of my article, but let's cover it quickly.
I see there are maybe some conceptual confusions.
When api.domain.com sets a cookie, it doesn't need to be available for domain.com. When domain.com fires a subsequent request to API, the cookie will be sent along with it. It's the API that needs the JWT, not domain.com. This can work if you set the API to accept CORS.
What I mean is that a session uses a cookie the same way its proposed for JWT to use it. Obviously they are different implementations.
The problem with sessions is not encryption, but what can be extracted from them. JWT can store minimal user object, so that API doesn't necessarily have to reach a database for that.
Great read! I have a question for you. Since storing credentials in the source code or cofig files is a big NO for all sorts of reasons, what do YOU do in cases where there is a SPA application that needs to authenticate with the backend (via JWTs) without any user interaction? I mean, lets say that we want only this app to be able to access specific back end resources, hence we must somehow provide the sourcecode of this app with some credentials to communicate to the back end to gain access (retrieve a JWT for future calls). For example, you have an application that accesses a backed web api and you want only this application to be able to access that particular API.
Hi Nikolaos, a critical topic you raised! This could easily render a dedicated article. But, as a quick overview:
It really depends on your infrastructure, environment and required security level.
Loading secrets on demand from an external, secure place, is recommended. Once it's loaded, the app can share it internally as an environment variable or keep it short-lived in a contextual variable to avoid leakage inside the app.
Once a secret is in the machine RAM and unencrypted, it's already exposed, though. Depending on how much security you need, it might be worth having secrets for different application areas or endpoints. If one secret is compromised, the damaged area is reduced.
There are basically two routes for implementation:
1. Managed services
This is my preferred choice, when financially feasible.
AWS, for instance, provides Secrets Manager:
It's a great service. There are two downsides:
Similarly, Azure has Key Vault and GCP has Key Management Service.
2. In-house secrets management
This will be tricky and I don't have enough expertise to advise on the best implementation from a security standpoint.
Nevertheless, one solution is using AWS Lambda to isolate my secrets and serve other parts of the application stack. A plugin for the Serverless framework makes it a bit easier.
Instead of calling a service like AWS Secrets Manager, I'd call my own AWS Lambda function, which will provide the secrets on-demand. It will be 10x cheaper: $0.004 per 10,000 requests.
Using IAM to control who has access to the secrets Lambda will provide reasonable level of security.
If I would work in a team using this approach, I'd completely isolate the Secrets Lambda from the rest of my stack (repo, infra-as-code, CI/CD workflow, everything). This would contribute to preventing leakage of secrets used in production.
You can get way fancier with this implementation, but it's already getting too lengthy... Hope this helps shed some light. 💡 😉
I believe this has already been discussed in the comments.
I'm not here to convince you of anything or prove anyone wrong. It's obvious that anyone can store anything in localstorage. If you're confident that storing sensitive credentials in it is perfectly fine, then it's not my responsibility to prove anything wrong or right... Just go for it.
Awesome post, thanks for sharing!
Question if i may:
I am working on legacy project that has sessions already in use. I have to add authorization part and i decided to use JWT, to avoid making extra request to session store.
Is it a good idea to use sessionId as secret when ever is needed to verify/sign JWT.
What you think about this idea, just to use sessionId as secret which is always unique for each user. In theory, this should make things more secure?
Hi, glad the article was helpful!
Two of the main advantages of JWT are:
How do you plan to implement #1 only with a session ID?
Unless your session ID is unique for each user and is permanent across time, you will still need to map each session ID to a real user in your database, defeating #2.
how to add layers of security, which will protect the integrity and, optionally, the content of the message? Vasiyam Specialist in Kerala
Hi, I was thinking recently how to implement auth and researched the idea of storing the token in httpOnly cookie. But had a problem with figuring out logout.
Main approach here is having invalidation API that will invalidate this token, but imagine a scenario when you are in some kind of public device and need to log out, but the internet is down.
You can not call invalidation API and can not delete HTTPonly cookie from the client, so the next user with this device will have access to your account and session.
Hi Sir, that is indeed something very important to consider, thanks for adding to the discussion!
My suggestion would be to set a relatively short life for the cookie so that it expires automatically, without an explicit
logOut
request comes to your backend. You can always renew the cookie expiration datetime when the user keeps logged and interacting with your app, to avoid disrupting the login session.The recommended expiration time will depend on the use case.
If you're dealing with financial funds, for example, perhaps a few minutes would be ideal. In most cases, an hour or maybe even a few hours might be ok.
Some apps will provide a "keep connected" checkbox, so the user can tell it's a trusted computer and cookies can last longer - perhaps days or months.
Social websites, like Facebook, will set a very long expiration time. That's because they want to keep your browser identifiable as you search the web interacting with like/share buttons, for example.
This is a beautifully written article about JWTs. Kudos to you.
Thank you for taking the time to read and express these kind words, Dewie! It means a lot to me, help validate the right direction! 🙌
What is develop advocate?
Hey Vladimir, I like this definition, by Wassim Chegham:
Nowadays it's also commonly referred to as "Developer Relations".
You'll also see "Technology Evangelist". I particularly dislike this title, because evangelism is about converting someone into a faith, which is a disservice in the tech world - not questioning other's beliefs, just think faith-based decisions are dangerous in tech.
Gotcha. Personally i think there is a way too many titles nowadays and hard to follow up all of them. People just get with some title and it goes viral. Take this as example, so we have at least 3 titles for the same thing :) Is it that team lead as well? Well, however, i appreciate the time to reply to my question :) All the best!
I agree, we need simplification and clarification of concepts.
The Tech Lead role is geared towards internal stuff within a company/project. There is relations to it, but internally.
Involves some level of:
Nice post. Anyway, just one question, how can I get the user information from the token that is stored in the cookies?
Thanks for the tips.
You're welcome Otu! Glad to have helped!
Hi Renato, thanks for the article but even more so for following up on all the comments. I may have learned more from the discussion than from the article itself.
Hi Samuel, it's very good to know the discussion was really helpful to you! Kudos to everyone that brought their thoughts and questions to enrich it. 👏 🍻
This is perhaps the main value in DEV: the ability to have friendly, respectful and intelligent conversations around tech issues that are open for everyone to learn from. 🙌