Author avatar
Fatih Kalifa
Imagineer, whatever that is
Sep 23, 20174 min read

Easy Authentication in Express using Passport

Auth0 was the authentication provider I chose for my blog dashboard. They're simple and easy to set up, but I mainly used them because I haven't had the time to build one myself.

Few months after my blog went live, I begin rewriting authentication logic to the blog API itself. I decided to use password-based authentication because it's the most straightforward, and considering this is for personal use, I don't have to think about email verification and such.

My goal with this rewrite is pretty simple: provide drop in replacement for auth0 authentication logic and easy read/write token for consuming API endpoint.

Choosing library

For this task I choose to use passport (and passport-local) for handling authentication in express, and bcrypt for hashing user password.

User creation and password hash

Implementing password hashing is quite straightforward: I provide static method in my mongo schema to hash password and validate them.

To create new user, use hashPassword static method first to get hashed password before creating user model instance.

User authentication

Passport has great documentation on how to implement different strategies. The most important part is initialize passport with your strategies using passport.use and call passport.authenticate to return express middleware to authenticate current request.

That's basically it.

Read/write token

As I mentioned before, the goal of this migration is to provide different read and write token to API consumer. Blog dashboard should have write access, and blog frontend should have read access only.

The way I implemented this is by using /user/login API endpoint which returns token instead of user. Blog dashboard can ask for read+write token by providing email+password. Blog frontend can call /user/login with empty data to receive read only token.

I added a slight modification to /user/login route handler

This token then will be used in other API endpoints to detect whether a request has proper permission or not. To achieve this, I create a middleware that sits before all API request (except request to /user/login)

By creating a function that returns a middleware, we can use this middleware to detect both read-only access and read-write access.

I also added small improvements like using separate expiration time for read only token and read-write token and in-memory LRU cache to retrieve token data so the server doesn't need to query to DB every time.