I challenged myself during last weeks to implement an authentication on a freshly created API. After digging around, I found that one of the best solution would be JSON Web Tokens. As understanding a concept passes by experimenting it, here is a post describing how to forge such a token in JavaScript.
- Generate Jwt Token With Secret Key
- Generate Jwt Token With Private Key Online
- Generate Jwt Token With Keypad
What is JSON Web Token (JWT)?
Create a public / private key pair for signing JWTs. Open a terminal window and use openssl to generate public and private key. Store the private key someplace safe and don't share it. The public key is used in the configuration section. Use this section to define 0 or more custom claims for your token. The claim type can be anything, and so can the value. If recipient of the token is a.NET Framework application, you might want to follow the Microsoft ClaimType names.
JSON Web Token (JWT) is an easy way to secure an API. When a user authenticates first on a server, using for instance a standard login form, the server creates a token. This token includes some personal data, such as username or email address. Then, this token is signed server-side (to prevent token integrity), and sent back to the user. Within each next request, user sends the token to establish emitter identity.
JSON Web Token is composed of three main parts:
- Header: normalized structure specifying how token is signed (generally using HMAC SHA-256 algorithm)
- Free set of claims embedding whatever you want: username, email, roles, expiration date, etc.
- Signature ensuring data integrity
Creating a JSON Web Token in JavaScript
JSON Web Tokens may be resumed by the following equations:
Base64 URL encoding
Note I wrote base64url
, not base64
. There is indeed two small differences between these two encodings:
- There is no
=
padding at the end, +
and/
characters are replaced by-
and_
respectively.
Implementing such a function can be achieved in JavaScript:
I use CryptoJS library to achieve the standard base64
encoding. This is a useful library whenever you want to assume some cryptographic, hashing or encoding tasks. This is perfectly the case, with the incoming HMAC signature.
To make this function work, you have to specify source as an array of UTF-8 bytes. It can easily be achieved using another utility function of CryptoJS: Utf8.parse
.
This extra call is not included into the base64url
function for signature commodity. But you are going to notice it later.
Generate Jwt Token With Secret Key
Creating our unsigned token
We can now encode our header and claims. Header is normalized, and contains two alg
and typ
fields indicating the used signature algorithm.
Generate Jwt Token With Private Key Online
After executing this first snippet, we got our unsigned token:
Signing our token
Finally, to ensure our token integrity, we should sign it with a secret. Signature is the HMAC SHA-256 (as specified in header) of our current token. And as usual, we should base64url
encode it.
No need of Utf8.parse
the output of HmacSHA256
. It is indeed already an array of UTF-8 characters. That’s why I didn’t include this method in our base64url
function.
Of course, you shouldn’t share your secret client-side. Tokens should be forged server-side. Otherwise, everyone would be able to modify your tokens and pass them as genuine.
If you execute this code, your signed token should look like:
There is plenty of libraries dealing with JWT. Creating tokens by hand is only a good idea to learn how they work. On a real project, don’t reinvent the wheel and use existing third-part tools, such as LexikJWTAuthenticationBundle for Symfony2 users or node-jsonwebtoken for Node.js developers.
Generate Jwt Token With Keypad
The full code of this post is available as a CodePen.
Another interesting resource: JWT.io