Use flatMap to validate JWTs issued by Azure Active Diectory

By flatMap, I actually mean RxJS. flatMap does play a big role though.

But first, a few finer points about JWTs. The entity that issues the JWT does not have to be the same entity that validates the JWT. These 2 entities can be 2 different servers or even belong to 2 different companies. They work as long as they share the same secret. This secret that is used by the issuer to sign the JWT is known by the resource server which uses it to verify the signature in the JWT. Many examples show this use case.

If we control both the issuer and the consumer of the JWT, then the above examples are a good fit to model after.

A lesser known fact or often overlooked is that JWTs can also be signed with public/private keys pairs. Azure Active Directory (AAD) uses this approach.

So for this post, assume we are trying to secure some NodeJS REST APIs with AAD-issued JWTs. How can we verify the signature in a JWT using RxJS flatMap?

There is already a NodeJS package https://github.com/dei79/node-azure-ad-jwt that does this. This library uses the callback model, which is fine. I just want to show how we can do the same with RxJS.

So let’s forget for a moment about the cache used by this library, and we have to rewrite this async library in a synchronous way, the pseudo code would look like:

In the pseudo code above, the blue-shaded boxes represents async calls. From the diagram, the starting input is a JWT. Once we get a certificate (public key) we can call a helper function to verify the JWT by passing the JWT itself and the certificate.

First let’s combine all helpers function into a util-like module called jwtaadUtils.

Let’s give credit to https://github.com/auth0/node-jsonwebtoken here.

So there are 3 helpers functions getTenantId(jwtString), convertCertificateToBeOpenSSLCompatible(cert) and verify(jwt, certificate). Treat them just like blackboxes as there’s no Rx or anything special. Pass input, return output.

getTenantId(jwtString) takes a JWT string and returns the tenantId.

convertCertificateToBeOpenSSLCompatible(cert) puts he certificate in a certain format.

verify(jwt, certificate) was already mentioned above. It takes a JWT and certificate, decodes and verifies if the signature in the JWT is valid or not.

Now comes the Rx part which is the essence of this post “How to use flatMap to validate JWTs issued by AAD?”

So just replace line 38 with the JWT you get from AAD, and run. You will see the decoded JWT and whether it’s valid or not.

Written by

Driven by passion and patience. Read my shorter posts https://dev.to/codeprototype (possibly duplicated from here but not always)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store