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.
Auth0 Node.js API SDK Quickstarts
curl --request GET \ --url http://localhost:8000/path_to_your_api \ --header 'authorization: Bearer YOUR_ID_TOKEN_HERE…
Create and Verify JWTs with Node.js
JWT, access token, token, OAuth token.. what does it all mean?? Properly known as "JSON Web Tokens", JWTs are a fairly…
Using JSON Web Tokens with Node.js
Front end frameworks and libraries such as Ember, Angular, and Backbone are part of a trend towards richer, more…
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.