Passport to Fun: A Joyful Guide to Authenticating Users with Passport.js and TypeScript

Passport to Fun: A Joyful Guide to Authenticating Users with Passport.js and TypeScript

Passport to Fun: A Joyful Guide to Authenticating Users with Passport.js and TypeScript was initially published on Monday January 16 2023 on the Tech Dev Blog. For the latest up-to-date content, fresh out of the oven, visit https://techdevblog.io and subscribe to our newsletter!

Passport to Fun: A Joyful Guide to Authenticating Users with Passport.js and TypeScript

Introduction

Welcome to this tutorial on how to use the passport.js library in TypeScript to authenticate users in an express backend! In this tutorial, we'll go over the basics of setting up passport.js and configuring it to work with TypeScript, as well as some best practices for authenticating users in your express backend.

This tutorial assumes that you have a basic understanding of express, TypeScript, and JavaScript. If you're new to any of these technologies, first familiarize yourself with them before proceeding.

Step 1: Installing Dependencies

The first step is to install the necessary dependencies. You'll need to have express and passport installed in your project. You can install these packages using npm by running the following command:

npm install express passport

Step 2: Setting up TypeScript

Next, you'll need to set up TypeScript in your project. If you're starting a new project, you can use the tsc command to initialize a new TypeScript project. If you're working on an existing project, you'll need to configure your project to use TypeScript.

Step 3: Creating a Passport Strategy

Now that you have passport and TypeScript set up, it's time to create a passport strategy. A passport strategy is used to authenticate users. It is typically created by extending the PassportStrategy class.

For this tutorial, we'll be using the LocalStrategy, which allows users to authenticate using a username and password. To create a LocalStrategy, you need to import the PassportStrategy class from the passport module and the Strategy class from the passport-local module. Then extend the PassportStrategy class and implement the authenticate method.

Here's an example of a LocalStrategy implementation:

import { PassportStrategy } from 'passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { AuthService } from './auth.service';

export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secretKey',
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}

Step 4: Configuring Passport

Once you've created your passport strategy, you'll need to configure passport to use it. This is typically done in the main entry point of your express application (e.g. app.js or server.ts).

First, import passport and your passport strategy. Then use the use method to configure passport to use your strategy.

Here's an example of how to configure passport to use a LocalStrategy:

import passport from 'passport';
import { JwtStrategy } from './jwt.strategy';

passport.use(new JwtStrategy());

Step 5: Protecting Routes

Now that you have passport configured, you can use it to protect routes in your express app. To do this, you'll need to use the authenticate method provided by passport. This method takes the name of the strategy you want to use (in this case, "jwt") as its first argument and an options object as its second argument.

Here's an example of how to protect a route using the LocalStrategy:

import express from 'express';
import passport from 'passport';

const router = express.Router();

router.get('/profile', passport.authenticate('jwt', { session: false }), (req, res) => {
  res.json({ user: req.user });
});

In this example, the /profile route is protected by the jwt strategy. Only users successfully authenticated using this strategy will be able to access this route.

Step 6: Logging In and Out

Now that you have your routes protected by passport, you need to add login and logout functionality to your application.

For logging in, you'll typically create a login route that accepts a username and password. Then use the authenticate method provided by passport to authenticate the user.

For logging out, you'll typically create a logout route calling passport's logout method.

Here's an example of how to create a login route:

router.post('/login', (req, res, next) => {
  passport.authenticate('jwt', (err, user, info) => {
    if (err || !user) {
      return res.status(400).json({
        message: 'Something is not right',
        user   : user
      });
    }
    req.login(user, { session: false }, (err) => {
      if (err) {
        res.send(err);
      }
      // generate a signed json web token with the contents of user object and return it in the response
      const token = jwt.sign(user, 'your_jwt_secret');
      return res.json({ user, token });
    });
  })(req, res);
});

And here's an example of how to create a logout route:

router.get('/logout', (req, res) => {
  req.logout();
  res.redirect('/');
});

Conclusion

And that's it! You've now successfully set up passport.js to authenticate users in your express backend using TypeScript. Remember that this is a basic example, and to always consider security and scaling factors when building your application.

I hope you found this tutorial helpful! If you have any questions or run into any issues, feel free to reach out for help.

Passport to Fun: A Joyful Guide to Authenticating Users with Passport.js and TypeScript was initially published on Monday January 16 2023 on the Tech Dev Blog. For the latest up-to-date content, fresh out of the oven, visit https://techdevblog.io and subscribe to our newsletter!

Did you find this article valuable?

Support Tech Dev Blog by becoming a sponsor. Any amount is appreciated!