JWT - it's kinda like sessions but without the sessions
-
While browsing the 'net, I found a neat little IETF draft standard called JWT (JSON Web Tokens).
Basically, the idea is that instead of having sessions on the server and a cookie to match a HTTP request to one of those sessions, one or more claims (i.e. user ID or admin status) are stored in a JSON object which is then signed by the server. (currently through either HMAC, RSA or ECDSA)
The client then stores this in usually either localStorage or sessionStorage and sends it along in an HTTP header with any request requiring authorization.For example:
- client logs in with username "Example" and password "password"
- server if user and password match, issue a JWT containing the payload
{ 'userId': 47 }
and send it to the client - client stores the JWT in sessionStorage
- (later) client creates a new topic and sends the JWT along in the
Authorization
HTTP header - server validates the signature in the JWT from the
Authorization
header with their own secret/key and if it's OK, uses the data from the JWT in the processing of the request
(in this case, theuserID
of 47 is used as creator of the topic)
Pros of JWT:
- The server doesn't need to store sessions!
=> less load on the server
& no shared session store is needed when scaling horizontally as long as all instances share a secret or public/private keypair - No cookies => no CSRF!
Cons:
- XSS becomes more dangerous - any malicious script with access to the client's localStorage or sessionStorage for a site can fully impersonate the user until the token expires or is deletes
There might be more cons & pros, I am neither good nor experienced enough to fully understand everything
("everything" is a lot though, I do have trouble with way less than that anyway, don't take my words for granted, do your own research, etc. etc. you know the drill )
Some links:
- General introduction: http://angular-tips.com/blog/2014/05/json-web-tokens-introduction/
- Slightly more detailed introduction with INFOGRAPHICS(ish): https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
- Web-based token decoder: http://jwt.io/
- Express middleware: https://www.npmjs.com/package/express-jwt