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.
I believe the libraries I'm attempting to use in dotnet core are trying to load a cert as an X509 then get the RSA Private key to send into a jwt.Encode method. I am not able to just use the pem file. Encode or Decode JWTs. Paste a JWT and decode its header, payload, and signature, or provide header, payload, and signature information to generate a JWT.
What is JSON Web Token (JWT)?
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
Generate Jwt Token With Private Key Online
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.
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.
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:
Generate Jwt Token With Secret Key
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.
The full code of this post is available as a CodePen.
Another interesting resource: JWT.io
In this article we will see how we can create and sign a JWT token with the RS256 algorithm. This function is complementary to the validate function I posted some time ago.
Here is the Sign(...)
function that can create a RS256 signed JWT token. It makes use of the BouncyCastle library. It is available as a NuGet package with version 1.8.1.
Here are some helper functions used in the above snippet.
The helper functions are the same ones found in the validate function.
Generate Jwt Token With Private Key
This function is based on the code snippet found in this SO question.
Update 1: You can check this post here, where I have created a C# library that manages Jwt tokens.
Generate Jwt Token With Keyboard
Update 2: If you are having trouble making your keys work, have a look in my Check your RSA private and public keys post and make sure to check the Additional Resources section as well