Generate Jwt Token With Key

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.

Generate Jwt Token With Private Key Java

If you are going to use multiple signing keys, it is common practice to create a random ID which identifies the key, and store that ID with the key in your database. When you create JWTs, set the kid field of the header to be this ID. Then when verifying JWTs, this kid field will tell you which signing key should be used for verification. Within the App Credentials page of your JWT app, you will see an option to View JWT Token. Here you can quickly generate a temporary token using the current API Key and Secret for the given expiration time. This single temporary token can then be used to test Zoom APIs, but should never be used in production applications. 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. 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.

Secret

You can create a custom token with the Firebase Admin SDK, or you can use a third-party JWT library if your server is written in a language which Firebase does not natively support. Before you begin. Custom tokens are signed JWTs where the private key used for signing belongs to a Google service account.

Generate Jwt Token With Secret Key Online

The helper functions are the same ones found in the validate function.

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.

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

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.

What is JSON Web Token (JWT)?

Generate

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:

Generate Jwt Token With Keyboard

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.

Generate Jwt Token With Key

After executing this first snippet, we got our unsigned token:

Jwt

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.

Generate Jwt Token With Private Key C#

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 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

Comments are closed.