Implementing Passport authentication for Steam, transitioning from Express to NestJS

I have embarked on the task of transitioning an express project to nestjs. How can I achieve the same functionality in Nestjs as shown in the working code snippet from Express below? (The code simply redirects to the Steam sign-in page)

/* eslint-disable space-before-function-paren */
// Include all required packages
var express = require('express');
var passport = require('passport');
var session = require('express-session');
var passportSteam = require('passport-steam');
var SteamStrategy = passportSteam.Strategy;
var app = express();
// Define a port
var port = 4000;
// Start the server
app.listen(port, () => {
  console.log('Listening, port ' + port);
});

// Setup the SteamStrategy
passport.serializeUser((user, done) => {
  done(null, user);
});

passport.deserializeUser((user, done) => {
  done(null, user);
});

// Initialize Strategy
passport.use(
  new SteamStrategy(
    {
      returnURL: 'http://localhost:' + port + '/api/auth/steam/return',
      realm: 'http://localhost:' + port + '/',
      apiKey: 'My API key',
    },
    function (identifier, profile, done) {
      process.nextTick(function () {
        profile.identifier = identifier;
        return done(null, profile);
      });
    }
  )
);

app.use(
  session({
    secret: 'Whatever_You_Want',
    saveUninitialized: true,
    resave: false,
    cookie: {
      maxAge: 3600000,
    },
  })
);
app.use(passport.initialize());
app.use(passport.session());

// Routes
app.get('/', (req, res) => {
  res.send(req.user);
});
app.get(
  '/api/auth/steam',
  passport.authenticate('steam', { failureRedirect: '/' }),
  function (req, res) {
    res.redirect('/');
  }
);

app.get(
  '/api/auth/steam/return',
  passport.authenticate('steam', { failureRedirect: '/' }),
  function (req, res) {
    res.redirect('/');
  }
);

How can I replicate this functionality in Nestjs? If I wish to create custom middleware for the passport library (serializeUser, deserializeUser), how would I go about it? The official Nestjs documentation provides examples of custom middlewares like the one below:

export function logger(req: Request, res: Response, next: NextFunction) {
  console.log(`Request...`);
  next();
};

But how do I incorporate passport middleware?

Answer №1

For those still seeking guidance, the following approach is recommended per the Nestjs documentation:

Assuming familiarity with setting up a nest application and handling steam authentication

  1. Begin by creating a controller dedicated to the /steam/auth path:
import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Request, Response } from 'express';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
 constructor(private readonly authService: AuthService) {}

 @Get('steam')
 @UseGuards(AuthGuard('steam'))
 steamLogin() {}
}
  1. Next, configure the steam strategy in a separate file named steam.strategy:
import { Strategy } from 'passport-steam';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';


@Injectable()
export class SteamStrategy extends PassportStrategy(Strategy) { 
    super({
      returnURL: 'http://localhost:3001/auth/return',
      realm: 'http://localhost:3001/',
      apiKey: 'Your API key',
    });
  }
  validate(identifier, profile, done) {
     // insert custom logic post successful login here
     
  }
  1. Remember to import the strategy within your auth.module:
import { Module } from '@nestjs/common';
import { SteamStrategy } from './steam.strategy';
@Module({
  providers: [SteamStrategy],
})
export class AuthModule {}

That wraps it up. Following this setup, you can proceed as usual with express!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of "this" in Vue.js 2.0

Seeking help with a VueJS issue. I am trying to create a voice search button that records my voice and prints it out in an input form. <input type="text" name="inputSearch" id="inputSearch" v-model="inputSearch" class="form-control" x-webkit-speech> ...

The custom directive in Vue utilizes the refreshed DOM element (also known as $el)

I am looking to create a custom directive that will replace all occurrences of 'cx' with <strong>cx</strong> in the Dom Tree. Here is my current approach: Vue.config.productionTip = false function removeKeywords(el, keyword){ i ...

Utilize the 'document / redirect' API within an express controller function

Here is how I have an API call using document / redirect: This call is made within HTML Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmln ...

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

Why am I seeing numbers in the output when I log the data from the res.write(data) function in Node.js?

While working with Node.js on my Raspberry Pi, I encountered an issue where reading a local file 'test.html' resulted in hex output instead of the expected HTML format. Can someone explain why this might be happening? Additionally, I am aware tha ...

Switching from PHP to jQuery or JavaScript can make for a

I've been attempting to convert this PHP code to jQuery or JavaScript without success. I'm still learning about jQuery and JavaScript Check out the original PHP code: <?php // Set timezone date_default_timezone_set('UTC'); ...

JavaScript- Tabbed Navigation with Lists as the Content

Currently, I am facing a frustrating issue in finding a suitable solution. My website uses tabs that utilize the UL, LI system, similar to most tab systems found in tutorials. The problem arises because the javascript on my site interferes with using the ...

The options in the dropdown menu vanish when interacting with a jQuery feature that relies on

Recently, I have found AJAX, JSON, and jQuery to be indispensable tools in my coding endeavors. The application I am working on is a replacement for a flawed one, and it is coming along nicely. Despite making progress with the AJAX method, I have encounte ...

Explore why query strings are excluded from the route path in Express

I came across something interesting in the express documentation at this link https://expressjs.com/en/guide/routing.html. It mentions that Query strings are not considered part of the route path. Can someone shed some light on this concept for me? I apo ...

What are the advantages of choosing Express over AngularJS?

It's clear to me that Express is typically found on the server, while Angular is usually on the client side. However, from what I've gathered, Angular has the capability to perform all the functions that Express can, such as: routing interactin ...

angular-chart custom tooltip positioning issue

Hello everyone! I'm having trouble fixing the tooltip position when hovering over a point. I've searched through various posts on StackOverflow and have tried all the examples provided in my implementation: https://github.com/chartjs/Chart.js/tr ...

The browser message states: Variable $? Not Found

As a newcomer to javascript (jquery/json), I've created code to display a chart using CanvasJS with a php/json data fetching script. However, I'm facing an issue where the chart is not rendering when I integrate my code. Upon inspecting the brows ...

What is the best way to retrieve a specific object from a JSON file using a Get request in a Node.js application?

My focus is on optimizing an API, which is why I'm working with only the data that's essential for my analysis. I've set up a route to extract specific objects, but I'm only interested in four of them: account_manager, fronter, closer, ...

What is the specific jQuery event triggered when utilizing the append function on a textarea element?

I am currently setting up a system to detect any modifications in a textarea: <textarea id="log-box__data"></textarea> Modifications are made to the textarea exclusively using jQuery's append method: $(document).on('click', &a ...

What is the proper way to send a list of lists from Ajax to Flask?

Attempting to send a list of list datatype data from a template using AJAX. Here is the code: Template (JS) var mydata = [['tom', 18, 'new york'], ['jack', 16, 'london']]; var data = new FormData(); mydata.forEach( ...

Having trouble retrieving data from Mongodb with Nodejs

Recently delving into the world of node.js, I've been experimenting with various features. At the moment, I have successfully fetched data from Twitter and stored it in a MongoDB database. Now, my goal is to retrieve this stored data from MongoDB and ...

How to fetch React route parameters on the server-side aspect

I encountered a challenge while working with ReactJS and ExpressJS. The user uploads some information on the /info route using React and axios. Then, the user receives route parameters from the server side to redirect to: axios.post('/info', Som ...

The value of $parent.$index will consistently be 0 in all cases

I am currently dealing with a nested ng-repeat situation where I am attempting to determine the parent's index. Due to the fact that it is being arranged post-process, the standard ng-repeat="(step_index, step) in flow" method is not working for m ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

Handling errors in a Node.js Express proxy application

I am facing an issue with my proxy code. Whenever the target server goes down, the application crashes displaying an error message Error: connect ECONNREFUSED. This is not ideal behavior for a proxy server as it should handle errors gracefully instead of c ...