When it comes to implementing authentication on web apps, one solution you’ll definitely hear about first are cookies. Cookie-based authentication uses a server side cookies to authenticate the user on every request. This means that you’ll need to keep a session store, whether it’s on a database or on something like Redis. A solution you’ll probably not hear as often is token-based authentication which relies on a signed token that is sent to the server on each request.
Alberto Pose over at Auth0 wrote a great blog post about Cookie vs Tokens, diagrams how both of these method works, and goes over the benefits of using a token-based approach for authentication.
There’s a relatively new standard called JSON Web Token that happens to be backed by companies like Firebase, Google, Microsoft, and Zendesk. There are already many libraries to handle encoding and decoding of this tokens in the backend.
The only difference when accessing the API will be the authentication method used. We’ll use JWT but third party application will use OAuth2.
The JWT Spec
JWT(pronounced “jot”) or JSON Web Token is a compact URL-safe representation format intented for space constrained environments such as HTTP Authorization headers and URL query paramaters. JWTs represent a set of claims as a JSON object that is encoded in a JSON Web Signature or JSON Web Encryption structure.
A JWT is represented as a sequence of base64url encoded values(with all trailing ‘=’ characters omitted.) that are separated by period characters.
The following is an example of a JWT Header
Base64url encoding of the JWT Header yields this encoded JWT Header value:
The following is an example of a JWT Claims Set:
Base64url encoding of the JWS Payload yields this encoded JWS Payload:
Computing the MAC of the encoded JWS Header and encoded JWS Payload with the HMAC SHA-256 algorithm(using the key ‘my_secret_key’) and base64url encoding the HMAC value, yields this encoded JWS Signature:
Concatenating these encoded parts in this order with period characters between the parts, yields this complete JWT.
You can read more about JWT in the submitted Internet-Draft.
An Example Scenario
First enters djangorestframework-jwt, a package I just released that provides JWT Authentication support for Django REST framework. It also provides an endpoint that can be used to obtain a JWT for a given username and password.
Once you’ve obtained a JWT, you can access resources that required authentication by passing the HTTP Authorization header.
A simple example of how this would be handled with jQuery and a Django REST Framework API endpoint with JWT Authentication.
And that’s a wrap!
And that’s basically it! I’d love to know what you think about JWT. Would you consider using token-based authentication? Any questions or feedback? Feel free to leave a comment.
Photo Credit: http://www.flickr.com/photos/number657/5179518226/