Thiago Dias
Thiago Dias

Reputation: 335

Prevent automatic redirect and get redirect URL of PassportJs "authenticate" method

I'm trying to encapsulate Passport.js strategies inside adapters, such as FacebookProviderAdapter, TwitchProviderAdapter, and so on... and for that, I need to "prevent" the default behavior of passport that automatically redirects the browser to the social network's OAuth URL

just to give more context, my abstract adapter it's something like this:

interface SocialAuthProviderInterface {
  generateRedirectUrl(): string;
}

I'm not using sessions, and I was able to use the callback "version" of the Passport.Js, but even tho it still redirects and I can't intercept the redirect URL string.

I realized that Passport is also tightly coupled to the Express.js library and sets everything inside its code, the documentation is very superficial to these aspects, how can I prevent the URL redirect and get the plain redirect URL out of any strategy?

my current test setup is the following:

/login/google is the starting endpoint that generates the oauth URL to google, this is the redirect that I want to prevent, I would like to have just the plain URL string.

app.get('/login/google', (request, response) => {
  passport.authenticate('google', { scope: ['profile email'], session: false}, (err, user, info) => {
    console.log(err, user, info)
  })(request, response)
})

app.get('/google', (request, response) => {
  passport.authenticate('google', { session: false }, (err, user, info) => {
    console.log(err, user, info)
  })(request);
})

Upvotes: 2

Views: 1331

Answers (2)

Vadim Prodan
Vadim Prodan

Reputation: 41

I would recommend create a new ServerResponse instance.

const passport = require('passport')
const { ServerResponse } = require('http')

app.get('/login/google', (request, response) => {
  const emptyResponse = new ServerResponse(request)

  passport.authenticate('google', { scope: ['profile email'], session: false}, (err, user, info) => {
    console.log(err, user, info)
  })(request, emptyResponse)

  console.log(emptyResponse.getHeader('location'))
})

Upvotes: 4

Thiago Dias
Thiago Dias

Reputation: 335

If anyone's is stuck with this problem, here's how I solved it:

for the URL redirect:

since passport js is highly coupled to the Express JS lib, inside the passport/lib/middleware/authenticate.js:315 you can see where it's defined the redirect function with Express js, the key part is the res.end(), where I manually replaced with a function to return the value of url

authenticate.js

enter image description here

my workaround

enter image description here

it's not pretty but it works :)

Upvotes: 1

Related Questions