How to sign your JWT tokens without exposing your private key using AWS KMS

Image for post

TL;DR

Node.js implementation using an asymmetric encryption key stored on AWS KMS to sign JWT tokens and verifying them using the public key. You can skip to the solution architecture.

JWT, Token Verification, and You

JWT tokens are an industry-standard, used mainly for user authentication.

It’s basically a JSON block with a signature attached, which allows you to verify that the content of the JSON was not tempered with. In the most common case, when your user logs in she gets a JWT token that is added to every request she sends, and this token is used to verify her identity.

How do you verify that your user is really who she claims to be? You take the signature from the JWT token and using your encryption key, you verify that it matches the content of the JSON. That’s called Token Verificaiton. The process of the creation of the signature in the first place is called Signing.

In order to sign and verify the token, you need an encryption method — either a symmetric or asymmetric (also called Public-Key encryption). In symmetric encryption, you’ll use the same key to sign and verify your token. In asymmetric encryption, you’ll use your private key to sign the token, and the public key to verify it.

What are we trying to solve?

Given a private key (either a symmetric or asymmetric), signing and verifying a string is quite simple, and there are multiple libraries for that.

However, to use most of these libraries you’ll need to have access to your secret key in order to sign the message (and if you’re using symmetric encryption, also to validate it). This is where things start to get messy: you need to keep your secret key somewhere that is reachable by your code, and at the same time, you’ll need to add a lot of protection layers on it to make sure no one gets his hands on it.

So what we want to solve is this: How to minimize the access to your private key and still be able to use it without too much fuss.

The first part of the solution is to use asymmetric encryption. In asymmetric you only need the private key to sign the token. The validation phase only requires the public key, and that can be, well, publicly available. This split will minimize the number of functions that need to access the private key.

The second part of the solution is to use AWS’s KMS service, which allows you to generate keys and use the KMS API to sign/validate messages without ever having direct access to the private key. Yes, that’s right: you’re generating a new private key, but you never get the private key. All you can do is ask AWS to use your key in order to sign or validate a token.

Let’s see how to do that.

#cloud #encryption #jwt #aws #development

Asymmetric JWT Signing using AWS KMS
2.55 GEEK