Token based + sessionless saml2 auth implementation using Passport, NodeJs

Problem at hand

What I wanted to make was a Node API with which I could authenticate through SAML 2.0 Identity Provider initially and using a token in subsequent requests. I found a bunch of clear information about each individual part but not how to integrate everything, hence this post.
A working example containing all the code can be downloaded from below link :
Zipped Example Code

saml 2.0 auth

Passport made this incredible easy with their saml strategy. As I mentioned above I am using as an IDP. There are many options available to test your solutions. You can refer my another article “How to setup app on and get issuer & entrypoint”.



This file contains implementation of both strategies. SAML strategies is really straight forward, nothing special we did. Simply standard implementation.
Other strategy, Bearer using redis to verify the token. I have created a simple library to use redis methods.


So that’s all the magic things. Now move to actual routes.


As you have noticed already, I am using two different strategies here. First to authenticate the user, SAML comes in between on following 2 routes.
1. /login
2. /login/callback
Once user gets authenticated, I am creating a token, saving it as a key in redis cache to verify it on subsequent requests. Rest other routes are using Bearer strategy. In bearer strategy we have already seen above, I am verifying the token coming in header.

How to test

Now the question comes, how to test this whole scenario.
It is fairly simple, Requestly(Chrome Extenstion) will help us here, to inject header in subsequent requests.


This is a chrome extension. Install it & enable the extension. You will see icon at top-right corner of your browser. Open it & create a rule as showing below.

To get the token, check console after login.
That’s all. Now you are ready to test the solution.
1. Open http://locahot:3000/. You will see “Unauthorized” as expected.

2. Now try http://localhost:3000/login. You are successfully logged-in, but still “Unauthorized”. Don’t worry, it is just because of wrong token in Requestly. Get the latest token from console & configure it.

3. Now refresh the page. You are logged-in, able to access secure routes using token.

That’s it.
Share your comments.

Recommended Post

Check out my another post on :
how to setup saml strategy dynamically to serve multiple client through same route

Reference: Narendra Singh (