Lurker News

Comments (249) 36 threads

tptacek21 replies#
This question comes up all the time on HN. I'm one of a bunch of people on HN that do this kind of work professionally. Here's a recent comment on a recent story about it:

https://news.ycombinator.com/item?id=16006394
The short answer is: don't overthink it. Do the simplest thing that will work: use 16+ byte random keys read from /dev/urandom and stored in a database. The cool-kid name for this is "bearer tokens".
You do not need Amazon-style "access keys" to go with your secrets. You do not need OAuth (OAuth is for delegated authentication, to allow 3rd parties to take actions on behalf of users), you do not need special UUID formats, you do not need to mess around with localStorage, you do not need TLS client certificates, you do not need cryptographic signatures, or any kind of public key crypto, or really any cryptography at all. You almost certain do not and will not need "stateless" authentication; to get it, you will sacrifice security and some usability, and in a typical application that depends on a database to get anything done anyways, you'll make those sacrifices for nothing.
Do not use JWTs, which are an increasingly (and somewhat inexplicably) popular cryptographic token that every working cryptography engineer I've spoken to hates passionately. JWTs are easy for developers to use, because libraries are a thing, but impossible for security engineers to reason about. There's a race to replace JWTs with something better (PAST is an example) and while I don't think the underlying idea behind JWTs is any good either, even if you disagree, you should still wait for one of the better formats to gain acceptance.

MattBearman#
Great answer. One thing I'd like to add is if you're using bearer tokens, make sure your API has an easy way to invalidate and regenerate them, as anyone with the bearer token has full access.
naikrovek#
Heck, I've been overthinking this. Thank you!
hundt1 reply#
Do you recommend signing requests?
tptacek2 replies#
No. The reason to sign requests is the same as the reason to support OAuth: so that the owner of the account can sign a request and give it to someone else to execute --- delegated authentication. Signed requests are finer-grained than OAuth is, but OAuth is much simpler and is the industry standard at this point. Don't do either thing until you absolutely need it, but then, start with OAuth.

Signed requests have burned a bunch of applications, more than have been burned by OAuth.

hundt2 replies#
Thanks for the response!

My thinking was that you might sign requests so that a request that was intercepted or inadvertently logged would not contain sufficient credentials to authorize arbitrary other requests for the indefinite future. It sounds like you do not consider that a significant enough issue to justify the complexity involved.

Continue this thread — 2 replies

dboreham4 replies#
Signed requests were also invented when the transport connection was in the clear: if the request were not signed then it could be modified in transit by an attacker. These days all sessions are encrypted (SSL/TLS) and so this concern doesn't exist (or doesn't exist if you trust the transport).

Continue this thread — 4 replies

everdev3 replies#
Don't major companies like Google use JWTs?
tptacek2 replies#
Major companies like Google do all sorts of dumb things, and, equally importantly, have gigantic well-funded security teams triple-checking what they do, so that the pitfalls in these standards are mostly an externality to them.

(The actual answer is: I have no idea what Google does with JWTs.)

logicuce5 replies#
With the right choice of algorithm, and if you control the code which interprets that JWT (whitelisting the alg and choosing the right library), I don't see a reason why JWT would be insecure.

Continue this thread — 5 replies

cookiecaper#
> have gigantic well-funded security teams triple-checking what they do

Yes! This is the answer to almost every "Well, it works for Google..." that comes up.
Alice: "It works for Google!"
Bob: "Sure, but how many PhDs does Google have on payroll managing it?"
Google has the resources, meaning dollars and reputation, that if they want to do something, they can hire anyone they want to make it possible. They frequently hire the authors of the programming languages and environments they use (that weren't already invented in-house), who can then customize everything to fit Google's needs just so.
Assuming you're a normal mortal corporation, getting the inventors of your platforms on board and committed to your problems specifically is no trivial matter, and you don't have an army of bona fide, credentialed computer scientists on payroll to patch any intervening rough spots, so "Google does it" is not really applicable.

iovrthoughtthis1 reply#
Do you have problems of the same complexity as google?
everdev#
No. But OP said that JWT is insecure, yet it seems widely adopted by top tech companies.
san_at_weblegit#
The answer would be yes with a rider. It would vary across the use cases and security requirements.
colinhowe1 reply#
Just a brief addition to this as a user of APIs. Allow me to create a new token and have two tokens for the same account. This makes rotation of tokens without loss of service possible :)
tptacek1 reply#
The downside to allowing multiple tokens is that in the real world, people will create new tokens for new deployment environments, but never delete the old ones, which will inevitably end up on Github somehow.
jdc05891 reply#
agreed, but its a solvable problem.

e.g. You can request a second token, but doing so immediately sets the currently active token to expire and be deleted in X days.

Continue this thread — 1 reply

dboreham2 replies#
One very important thing you didn't mention : you MUST force transport encryption (SSL/TLS) to be used (deny plaintext connections). This is because the bearer token can be stolen by eavesdropping and since it's a bearer token it can be re-used by anyone anywhere.

Also remember to time out the tokens: it is almost never a good idea to permit infinitely long login sessions (surprising how often I see this not done). Again remember to invalidate the token when the user changes their password.
I agree that OAuth is not necessary on its own but it can be appropriate if you are also supporting delegated authentication with various 3rd parties : make your own native auth just another OAuth provider.

tptacek1 reply#
You need transport encryption no matter what, not just for REST APIs. I'm just addressing the app design concerns.
iopuy4 replies#
Is it not true that Basic Authentication requires TLS due to transporting credentials as plain text but other variations encrypt the credentials at a higher level before being put on the wire? In that case why is TLS a necessity?

Continue this thread — 4 replies

stu_b1 reply#
RE: Denying plaintext connections. Totally agree & great if your clients connect directly to hosting you have full control over. The biggest problem I've come across is that cloud services like CloudFlare & API gateways (Tyk for example) don't have the option (or at least I couldn't find it) to disable HTTP traffic. Plenty offer to redirect HTTP to HTTPS but I haven't been able to refuse HTTP traffic outright.

Does anyone have any recommendations for services that do offer this? (or where those options are in the named services)

hirstys1 reply#
If you can install an open source Tyk gateway in your stack, you can use TLS on the Tyk Gateway to refuse HTTP outright. However, this isn't a Tyk cloud feature at present.

Continue this thread — 1 reply

kgraves#
> There's a race to replace JWTs with something better (PAST is an example) and while I don't think the underlying idea behind JWTs is any good either, even if you disagree, you should still wait for one of the better formats to gain acceptance.

Aside from PAST, I recently have come across this[0] (called branca) as I too was looking for an alternative to JWT. This seems to be based on Fernet, but according to the maintainer of this spec it isn't maintained anymore.
[0] https://github.com/tuupola/branca-spec

oxymoron2 replies#
I’ve frequently used the equivalent of HMAC_SHA512(long_secret,uid + ’|’ + timestamp) to generate a token on the server, which the client can retain and pass along requests, and can be verified on the server without persistence. I assume this is what you refer to as stateless authentication. While I agree that there are no real performance reasons to do so, it seems convenient to me every now and then. Is there a security reason to stop doing so?
bb88#
Only if the long_secret was made public.

Continue this thread — 1 more reply

Continue this thread — 13 more replies

barrystaes5 replies#
Do everything via HTTPS, disable HTTP. The login request (POST, dont use url query params) contains username + password. The API replies with a session token (a random string). You can store any metadata relating to this session token in your DB.

The API client should this token in every request that requires authentication, often in the header as `Authorization : Bearer 123TheToken456`.
JWT: If DB performance becomes a problem (or you want to expose signed session metadata) consider using JWT to provide session validation with the request itself. The downsides of JWT are that its often used to hold secret values (dont do this), or is a few kilobytes big which makes all requests slow, or stupid mistakes in signing and session validation that make it very insecure like allowing any request to just specify false permissions.

fimdomeio1 reply#
I basically do this with jwt. In my case jwt just contains the basic data that the front needs to find out who the user is and what it can do (user uuid and role). While obviously checking if action is allowed to user is done server side it's normally useful for the front end to also be aware.
jcadam#
Yea, I happen to be using JWT in the simplest way. Authentication only.

I don't even store role information in them, since authorization checks are performed on the server anyway.
If the client needs to know what a user is allowed to do with a resource (so it knows not to display certain buttons, etc.) I have the client do an OPTIONS call (with the token) to see what methods are allowed.
Lately, I've been thinking about replacing the whole JWT scheme with simple bearer tokens stored in the database, mostly because it would make revocation simple and I can't think of anything I would lose by giving up JWTs (a little storage space in the database?), and I don't think switching the type of bearer token I'm working with will actually be very painful implementation-wise. You know what, I'm adding a task to my backlog...

sethgecko3 replies#
Doesn't a session token violate the stateless principle ?
intellent#
If you use it for authorization only, it doesn’t.
kbutler1 reply#
Yes, it does.

If you want to be completely stateless, you need to send the authorization info on each request, probably as basic auth headers.
This is actually simpler than implementing the Bearer token, for both client and server, but requires that the client retain the non-expiring username and password, rather than retaining the expiring, session-specific Bearer token.

matwood6 replies#
> but requires that the client retain the non-expiring username and password

IMO, this makes this simpler solution a non-starter. It becomes way too easy to leak credentials.

Continue this thread — 6 replies

cdaven1 reply#
Yes, if you mean a token that identifies a session that is saved on the server somehow. But not a JWT, which is only saved on the client and verified on the server.
eropple1 reply#
"Stateless" refers to the app, not to its datastores, because that would be nonsensical.

JWT is also poorly specified (no protocol under any circumstances should use negotiation, it does not support revocation, and it has been hammered home by the best security folks I know that public key cryptography is what you do when you don't have any other choice) and dangerous to use. Avoid it. Do the simplest thing that can possibly work. That's a session token. If, in the far and unlikely future, you are so successful that a single database call is so harmful, then you have the money to hire someone who doesn't have to Ask HN this question.

Continue this thread — 1 reply

matwood3 replies#
I have found the above (sans JWT) to be the simplest, secure method. Do everything over HTTPS, use basic auth or post for the user/pass and return an expiring token, use that token as a Bearer token for all subsequent requests.
oozzee3 replies#
I’m mostley a FE person at the moment so forgive me for my ignorance but how does the server use the token passed to the client to do auth?

Does it keep a copy somewhere and check against it on every request?

pc862 replies#
> Does it keep a copy somewhere and check against it on every request?

Yes. The last time I did this we checked the X-Token header on every request, if it didn't exist or there were multiple we replied 401. If only one was there we checked a DB table of active tokens, if it wasn't there or had expired we replied 401. If it was there but wasn't associated with a role that had access to the requested resource, we replied 403. If it was not expired and had access we continued with the request.
As soon as you get away from "check authentication on every request" your attack vectors increase. As a bad actor, I no longer need to bypass your authentication, I just need to bypass whatever system you have in place to decide whether or not to authenticate me. That's generally going to be easier.

Continue this thread — 2 replies

matwood#
> Does it keep a copy somewhere and check against it on every request?

Yep, a store like Redis that has automatic row expiration is what I have used in the past. Most clients will often be bursty in their requests so a simple few second cache on API after verifying the token can also be useful/performant.

Continue this thread — 1 more reply

Continue this thread — 2 more replies

Continue this thread — 2 more replies

drderidder7 replies#
I highly recommend reading "The Do's and Don'ts of Client Authentication on the Web" [1] from MIT. It's rather old and not very well-known, but it's excellent. The concepts provide very useful background info that will serve you well no matter what technology you use to implement your HTTP services, including issues like session hijacking, etc. One of it's best recommendations: avoid roll-your-own solutions. Secondly, I recommend checking out the "auth" example from the expressjs repository on github [2]. It will provide a practical implementation example. Lastly, if you're considering using Express or any similar framework, I recommend checking out "route parameter preconditions". These seem to remain a little-known feature of Express, but they can be particularly useful for applying middleware to entire sets of routes, for example enforcing authentication on anything under a certain path. You can still find screen-casts for route-specific middleware and route parameter preconditions on the Express 2.x documentation site by TJ, the original author [3]. Some of the specific details may have changed in the newer versions of Express, but TJ's explanation of the concepts is simple and clear.

[1] https://pdos.csail.mit.edu/papers/webauth:sec10.pdf [2] https://github.com/expressjs/express/blob/master/examples/au... [3] https://expressjs.com/2x/screencasts.html

Continue this thread — 7 replies

jpalomaki12 replies#
Why not use either simple API key or HTTP basic auth? Both are simple to implement and supported by all the tools and libraries.

I would consider more complicated solutions only if you first come to conclusion that these simple things are not fit for the purpose.
True that some fancy token based solution may reduce database load, but if the API is doing something useful then that one primary key lookup and potentially the password hashing won't be a show stopper. Drawback with tokens and skipping the DB check is that you can't simply kill a client behaving badly. With API key you can just change the key and requests stop immediately (with MVP product this might be an issue, since maybe you have decided to add rate limits etc later).

Continue this thread — 12 replies

Load more comments