Giter Site home page Giter Site logo

discuss's People

Contributors

jaredhanson avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

discuss's Issues

What is Google oauth2 profile.id ?

I am trying to understand how to authenticate a person using passport-google-oauth20 .
The authentication request returns something called "profile". It seems that the only field useful for authentication is profile.id
It is a long number.
Is there any way to learn this number, for a given person, who has a gmail account?
Or, given a number, to know the person's gmail address?
It would seem to me, that the most reliable authentication would be by gmail address. But the Passport strategy passport-google-oauth20 only provides that mysterious profile.id . What is it? Is it unique? Permanent?

Warning email from Google re: Google+ API

We got this email from Google recently:

On March 7, 2019, all Google+ APIs and Google+ Sign-in will be shut down completely. If you see calls to people.get, these can be the result of using the Google+ Sign-In feature in your application, which is now fully deprecated and is being shut down. Developers should migrate from the Google+ Sign-In feature (https://developers.google.com/+/web/signin/) to the more comprehensive Google Sign-in (https://developers.google.com/identity/) authentication system.

Then we noticed in the Google Developer portal that our project has had 134 calls to plus.people.get in the last month.

We're using https://github.com/jaredhanson/passport-google-oauth for Google Sign-in.

But we searched our entire code, even node_modules, and couldn't find any reference to plus.people.get.

Any ideas where this is coming from? And how we can update our code to avoid Google Sign-in issues come March?

Thanks!

Sending DB information from strategy callback?

When hitting the strategy callback I can either create a user if he doesn't exist and send that profile back, or if he does exists, simply send that user back.

However, on the client side, I will be redirecting a user to different routes depending on whether he's a brand new user or an existing one. How can I send this info from the strategy callback, back to the client? Is this possible?

const strategyCallback = async (accessToken, refreshToken, profile, cb) => {
    const email = profile.emails[0].value;
    try {
        let user = await models.user.findOne({ where: { email } });
        if (!user) {
            user = await models.user.create({ email });
            // Send info from here that the user is newly created
        }
        // Send info from here that the user is an existing one
        return cb(null, user);
    } catch(e) {
        return cb(e, false);
    }
}

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_SECRET,
    callbackURL: process.env.GOOGLE_CALLBACK,
    },
    strategyCallback
));

GoogleOAuth2.0- Bad Request

Hi, I'm quite new to using this package. I am trying implement OAuth sign-in with google using passport-google-oauth20.

But whenever I try to to sign in, It just sends a 'Bad Request' response to to my browser and I am not getting errors in the terminal.

Here's what I've implemented in index.js

const userSchema = new mongoose.Schema({
    email: String,
    password: String,
    googleId: String,
    secret: String
});

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(function (user, done) {
    done(null, user.id);
});

passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
        done(err, user);
    });
});

passport.use(new GoogleStrategy({
        clientID: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET,
        callbackURL: "http://localhost:8080/auth/google/oauth",
        userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
    },
    function (accessToken, refreshToken, profile, cb) {
        //console.log(profile);

        User.findOrCreate({
            googleId: profile.id
        }, function (err, user) {
            return cb(err, user);
        });
    }
));

app.get("/auth/google/oauth",
    passport.authenticate('google', {
        failureRedirect: "/login"
    }),
    function (req, res) {
        // Successful authentication, redirect to profile page.
        res.redirect("/profile");
    });

It's been two days since I'm trying to figure out a solution on Github, Stackoverflow etc. but nothing seems to have worked out so far.

Authentication fails when Using passport with vhost

I have a Sails application and the authentication using passport works just fine when it is a single domain app. I am now trying to convert the app to using subdomains (foo.example.com, bar.example.com), all of which points to the same sails server. The session works only for the same sub-domain, for example, if the user is logging in from foo.example.com, then the user s able to access pages under the same sub domain...but not under bar.example.com.
req.isAuthenticated() is returning false when redirecting to a subdomain different from the one that was authenticated. How can I ensure the authentication is across the sub-domains? Any help is much appreciated.

Infinite redirection between auth/callback and /login post authentication.

hi,
I am trying to integrate passport.js and passport-azure-ad OIDC Strategy in node.js server. entire application stack is as below.
front end: Vue.js
back end: Node.js server + Oracle DB for further authorization.

Actual Issue: After calling [auth/callback] we receive response from Capture(internal system) in server/auth.js passport.use() async function. --> than it goes to serializeUser() after sutffing it goes to the callback function of '/auth/callback' where we log this line. We received authorized flag. and isAuth flag value is: true then again it redirects to /auth/callback then deserialize then /login and so on.

log image is as below

server_log

Chrome developer tool network tab

chrome_network_1

more from chrome developer tool network tab
chrome_network_2

server directory structure is like below

server_directory_structure

node server code is as below:

filename : server/webServer.js
you can remove esg-icp-common as its for logger purpose.
auth.initialize(); is initializing passport from next file.

const settings = require('../settings');
const express = require('express');
require('express-async-errors');
const app = express();
const passport = require('passport');
const OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const methodOverride = require('method-override');
const http = require('http');
const flash = require('flash');
const router = require('./routes');
const auth = require('./auth');
const cookieSession = require('cookie-session');
const expressSession = require('express-session');
const httpContext = require('express-http-context');
const logger = require('esg-icp-common').logger;
const globalTunnel = require('global-tunnel-ng');
const {
    Capture
} = require('esg-icp-common');
const capture = new Capture(settings.capture);


class WebServer {
    async initialize() {
        logger.info('Initializing web server');

        logger.info('Initializing global tunnel');

        globalTunnel.initialize({
            host: settings.proxyIP,
            port: settings.proxyPort,
            sockets: 50 //optional pool size for each http and https
        });


        app.use(httpContext.middleware);
        app.use(bodyParser.json());

        // Parsers
        app.use(bodyParser.json({
            limit: '100mb'
        }));
        app.use(bodyParser.urlencoded({
            extended: true
        })); //it was false in old version.
        app.use(cookieParser()); // old settings: settings.session.cookieKey need to pass into cookieParser


        app.use(expressSession({
            //secret: settings.session.cookieKey,
            secret: 'keyboard cat',
            resave: true,
            saveUninitialized: false,
            maxAge: 24 * 60 * 60 * 1000
        }));


        function ensureAuthenticated(req, res, next) {
            if (req.isAuthenticated()) {
                return next();
            }
            res.redirect('/login');
        }

        app.get('/', ensureAuthenticated, (req, res) => {
            res.send('<meta http-equiv="refresh" content="0; /" />');
        })
        auth.initialize();
        // Logging
        app.use(logger.httpLogger);
        app.post('/js_error', (req, res) => {
            logger.error(`JS ${req.body.error}`);
            res.json({
                success: true
            });
        });

        app.use(flash());
        // Point static path to dist
        app.use(express.static('ui/dist'));
        app.use(express.static('ui/static'));

        app.use(passport.initialize());
        app.use(passport.session());
        app.use(router);


        // Error handling, should be last.
        app.use((err, req, res, next) => {
            if (res.headersSent) {
                next(err);
            } else {
                logger.error(err.stack || err.message || err);
                res.status(500).send('500 Internal Server Error');
            }
        });

        /**
         * Create HTTP server.
         */
        this.server = http.createServer(app);
        await new Promise((resolve, reject) => {
            this.server.listen(settings.port, () => {
                logger.info(`Web server is up and running on port: ${settings.port}`);
                resolve();
            });
        });
    }


    close() {
        globalTunnel.end();
        this.server.close();
    }
}

module.exports = new WebServer();

File Name: server/routes.js
this file contains all routes register here so as a middle wear we can use this in the webServer.js

const router = require('express').Router();
const httpContext = require('express-http-context');
const settings = require('../settings');

function ensureAuth(req, res, next) {
  if (settings.isAuthActivated) {
    if (req.path.startsWith('/login') || req.path.startsWith('/logout') || req.path.startsWith('/auth/callback') || req.path.startsWith('/unauthorized') || req.path.startsWith('/favicon.ico')) {
      return next();
    }
    else {
      const timeNow = parseInt(new Date().getTime() / 1000);
      if (req.user) {
        if (timeNow < req.user.exp) {
          httpContext.set('user', req.user);
          return next();
        }
      }
      if (req.path === '/') {
        logger.info('Redirecting to auth/login');
        res.redirect('/login');
      } else {
        res.status(401).json({message: 'Authentication Required', success: false});
      }
    }
  }
  else {
    return next();
  }
}

router.use(ensureAuth, require('./routes/auth'));
router.use(ensureAuth, require('./routes/reports'));
router.use(ensureAuth, require('./routes/capture'));
router.use(ensureAuth, require('./routes/events'));
router.use(ensureAuth, require('./routes/resources'));

module.exports = router;

File Name : server/auth.js
please ignor this call capture.getContactByEmail()
consider globaltunnel on/off is require to make this code work behind corporate proxy.

const passport = require('passport');
const settings = require('../settings');
const { logger, Capture } = require('esg-icp-common');
const capture = new Capture(settings.capture);
const httpContext = require('express-http-context');
const OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
const globalTunnel = require('global-tunnel-ng');

class PassportAuth {
  getSessionInfo() {
    const user = httpContext.get('user');
    return user
      ? `${user.KEYID} ${user.EMAIL}`
      : '';
  }



  initialize() {
    passport.serializeUser(function (user, done) {
      console.log('in serialize');
      done(null, user.id); // here user info is available.
    });

    passport.deserializeUser(function (id, done) {
      console.log('in deserialize');
      //done(null, user);
      User.findById(id, function(err, user) {
        done(err, user);
      });
    });

    passport.use(new OIDCStrategy({
        callbackURL: settings.creds.returnURL,
        redirectUrl: settings.creds.redirectUrl,
        realm: settings.creds.realm,
        clientID: settings.creds.clientID,
        clientSecret: settings.creds.clientSecret,
        oidcIssuer: settings.creds.issuer,
        identityMetadata: settings.creds.identityMetadata,
        skipUserProfile: settings.creds.skipUserProfile,
        responseType: settings.creds.responseType,
        responseMode: settings.creds.responseMode,
        scope: settings.creds.scope,
        allowHttpForRedirectUrl: settings.creds.allowHttpForRedirectUrl
      },
      async function (iss, sub, profile, accessToken, refreshToken, done) {

        if (!profile.oid) {

          console.log(util.inspect(profile));
          return done(new Error("No OID found"), null);
        }
        console.log(profile.emails[0]+':: in the passport async function call back.');

        globalTunnel.end();
        capture.getContactByEmail(profile.emails[0]).then((response)=>{
          const contactsByEmailResult = response;
          console.log('response from Capture : Authorization Done.');
          globalTunnel.initialize({
            host: settings.proxyIP,
            port: settings.proxyPort,
            sockets: settings.proxySockets
          });
          if (contactsByEmailResult.count === 0) {
            done(null, {
              code: 'Unauthorized',
              message: `Contact not found for: ${profile.emails[0]}`
            });
          } else if (contactsByEmailResult.count === 1) {
            Object.assign(profile, contactsByEmailResult.contacts[0]);
            done(null, {code: 'Authorized', exp: null, profile: profile});
          }
          else {
            done({
              code: 'Unauthorized',
              message: `Too many contacts returned for email: ${profile.emails[0]}`
            });
          }
        },(error)=>{
          console.log(error);
        }).catch(error => {
          console.log(error)
        });
      }
    ));
  }
}

module.exports = new PassportAuth();

File Name server/routes/auth.js
this file is containing all routes to carry out authentication process.

const router = require('express').Router();
const passport = require('passport');
const settings = require('../../settings');
const logger = require('esg-icp-common').logger;

router.get('/favicon.ico', (req, res) => {
  res.status(204);
});


router.post('/auth/callback',
  passport.authenticate('azuread-openidconnect', {
    failureRedirect: '/login'
  }),
  function (req, res) {
    if (req.user.code == 'Authorized') {
      console.log('We received authorized flag. and isAuth flag value is: '+  req.isAuthenticated());
      res.redirect('/');
      //res.end('yes');
      //res.send('<meta http-equiv="refresh" content="0;/" />');
    } else {
      req.user = null;
      //req.logout();
      res.redirect('/unauthorized');
    }
  });


router.get('/unauthorized', (req, res) => {
  // TODO: create a page
  res.send("<p> The email link  is : <a href='mailto:[email protected]?Subject=Authorization%20request&body=Hi Team, please authorize me My email address is :' target='_top'>here</a></p>");
});

router.get('/login', passport.authenticate('azuread-openidconnect', {
  failureRedirect: '/login'
}), (req, res) => {
  console.log(req.user);
  console.log('Login was called in the Sample');
  res.redirect('/');
});


router.get('/logout', function (req, res) {
  req.logout();
  res.redirect(settings.destroySessionUrl);
});


router.get('/session-user', (req, res) => {
  const user = req.user;
  if(settings.isAuthActivated === true ){
    if(user != undefined) {
      res.send({
        name: user.NAME,
        email: user.EMAIL,
        issuerId: user.KEYID
      });
    }
    else{

    }
  }
  else{
    res.send({
      name: settings.dummyUser.name,
      email: settings.dummyUser.email,
      issuerId: settings.dummyUser.keyId
    });
  }
})

module.exports = router;

FacebookStrategy not providing profile object, while providing a valid access token.

I wrote an API that uses Passport and FacebookStrategy to login with a Facebook account. This login flow was working till today when suddenly FacebookStrategy stopped providing the profile object, weirdly providing accessToken. Here's what I coded:

const passport = require('passport');
const User = require('../models/User');
const { Strategy: FacebookStrategy } = require('passport-facebook');
const {
  FACEBOOK_CONFIG,
} = require('../config');

module.exports = () => {

  passport.serializeUser((user, done) => done(null, user.id));
  passport.deserializeUser((id, done) => {
    User.getUserById(id, function(err, user) {
      done(err, user);
    });
  });

  const callback = (accessToken, profile, cb) => {
    console.log(`${accessToken}, ${profile}`);
    User.findOne({ 'facebook.id': profile.id }, (err, user) => {
      if (err) return cb(err);
      if (user) {
        User.findOneAndUpdate({ 'facebook.id': profile.id }, { 'facebook.accessToken': accessToken }, (err) => {
          if(err) console.log(err);
          else console.log('accessToken trocado.');
        });
      }
      else {
        var newUser = new User();
        newUser.facebook.id = profile.id;
        newUser.facebook.token = profile.token;
        newUser.facebook.name = `${profile.name.givenName} ${profile.name.familyName}`;
        newUser.facebook.photoUrl = profile.photos[0].value;
        newUser.facebook.accessToken = accessToken;
        if (typeof profile.emails !== 'undefined' && profile.emails.length > 0)
          newUser.facebook.email = profile.emails[0].value;
          newUser.save((err) => {
            if (err) throw err;
            return cb(null, newUser);
          });
      };
    });
   cb(null, profile);
  };

  passport.use(new FacebookStrategy(FACEBOOK_CONFIG, callback))
}

I really don't know if I did something wrong. Any help is appreciated.

Thanks!

Is passport-facebook-token not an official strategy?

I'm writing an API in Node that will be used by a mobile app client. I have implemented client-side authentication via Facebook within the app so I have a valid Facebook JWT. Given my research, it appears passport-facebook-token is what I should use to authenticate with my API but it is not listed on the official Passport website.

Is this strategy safe to use? Can I actually just use passport-facebook for my needs?

Any help is much appreciated! Thanks.

Passport does not work when sameSite='none'/secure are set with express-session and cookie-session.

I want the passport cookies to be sent with sameSite='none' and secure=true to bypass the sameSite restrictions enforced by the recent Chrome update. But when I set the sameSite and secure options in express-session or cookie-session, req.session no longer persists the passport state. And req.user is also no longer set.

The passport works on localhost when sameSite and secure are not set. But fails when I deploy the front end and back end to Heroku. I know Heroku deploys to https secured websites, which is one possible reason for this issue.

Does anyone know what I can do to get around this? I just want to deploy an app with Google authentication but this sameSite restriction is really messing up my production deploy.

cookiesession

failureRedirect doesn't redirect as expected.

Hi.
As i'm trying to handle where a user clicks 'Cancel' on the Facebook prompted modal, instead of being redirect to the failureRedirect, I'm getting this:

FacebookAuthorizationError: Login Error: There is an error in logging you into this application. Please try again later.
    at Strategy.authenticate (/sample-app/node_modules/passport-facebook/lib/strategy.js:79:23)
at attempt (/sample-app/node_modules/passport/lib/middleware/authenticate.js:361:16)
at authenticate (/sample-app/node_modules/passport/lib/middleware/authenticate.js:362:7)
at Layer.handle [as handle_request] (/sample-app/node_modules/express/lib/router/layer.js:95:5)
at next (/sample-app/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/sample-app/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/sample-app/node_modules/express/lib/router/layer.js:95:5)
at /sample-app/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/sample-app/node_modules/express/lib/router/index.js:335:12)
at next (/sample-app/node_modules/express/lib/router/index.js:275:10)

The URL is which displays this error trace:

http://localhost:3000/auth/facebook/callback?error_code=1349003&error_message=Login+Error%3A+There+is+an+error+in+logging+you+into+this+application.+Please+try+again+later.#_=_

This is my settings (very similar to the example in the documentation: http://www.passportjs.org/docs/facebook/

This is my sample:
server.js

const express = require('express');
const app = express();

const passport = require('passport')
    , FacebookStrategy = require('passport-facebook').Strategy;


app.use(passport.initialize());
app.use(passport.session());

passport.use(new FacebookStrategy({
        clientID: FACEBOOK_APP_ID,
        clientSecret: FACEBOOK_APP_SECRET,
        callbackURL: 'http://localhost:3000/auth/facebook/callback'
    },
    function (accessToken, refreshToken, profile, done) {
        done(null, profile);
    }
));

passport.serializeUser(function (user, done) {
    console.log('we are calling serialized user, user to serialized:');
    console.log(user);
    done(null, 'this is the user');
});

passport.deserializeUser(function (id, done) {
    console.log('we are calling de serialized user, user to de serialized:');
    console.log(id);
    done(err, {message: 'this is the user'});
});

app.get('/auth/facebook', passport.authenticate('facebook'));

app.get('/auth/facebook/callback',
    passport.authenticate('facebook', {
        successRedirect: '/success',
        failureRedirect: '/failure'
    }));

const path = require('path');

app.get('/login', function (req, res) {
    res.sendFile(path.join('/sample-app/lib/login.html'));
});

app.get('/success', function (req, res) {
    res.sendFile(path.join('/sample-app/lib/success.html'));
});

app.get('/failure', function (req, res) {
    console.log("We have failed you");
    res.redirect('/login');
});

app.listen(3000, () => {
    console.log("I'm listening!");
});

login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/auth/facebook">Login with Facebook</a>
</body>
</html>

success.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Success with facebook!</h1>
    <a href="/auth/facebook">Login with Facebook</a>
</body>
</html>

Running on:

dockerfile:
FROM-> node:10.2.1-slim
* cat /etc/issue => Debian GNU/Linux 8 \n \l
* cat /etc/debian_version=> 8.10

NPM
express : 4.16.3
passport: 0.4.0
passport-facebook: 2.1.1

Expected:
be redirected to localhost:3000/failure [ notice, the successRedirect working great, i'm redirected to http://localhost:3000/success#_=_]

How to pass a password to a user session if there is no req in the strategy

Are you looking for help?

Yes.
This is not an instagram problem, it's your library.
Is this a security issue?

No.

I can not safely transfer data to the callback success in order to be able to record a user session.
Expected behavior

Something like this:

passport.use(new InstagramStrategy({
    clientID: INSTAGRAM_CLIENT_ID,
    clientSecret: INSTAGRAM_CLIENT_SECRET,
    callbackURL: 'http://'+my_ip+'/login/auth/instagram'
  },
  function(accessToken, refreshToken, profile, done, req) {
    process.nextTick(function() {
    req.session.password = "mypass"; // GOOD
});
    	return done(null, profile);
    });
  }
));

Actual behavior

This code:

router.get('/auth/instagram',
	passport.authenticate('instagram', {
		failureRedirect: '/'
	}),
	function(req, res) {
		req.session.password = // How do I get data so that no errors occur?
		res.redirect('/profile');
	}
);

I need to transfer data safely to record the session.
Steps to reproduce

let o = {};
passport.use(new InstagramStrategy({
    clientID: INSTAGRAM_CLIENT_ID,
    clientSecret: INSTAGRAM_CLIENT_SECRET,
    callbackURL: 'http://'+my_ip+'/login/auth/instagram'
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function() {
         let pass = "password";
         o.pass = pass; //BAD CODE
return done(null, profile);
    });
  }
));

I can not make a website because of this!

Environment

Operating System: Linux arch 4.16.9-1-ARCH #1 SMP PREEMPT Thu May 17 02:10:09 UTC 2018 x86_64 GNU/Linux
Node version: v10.1.0
passport version: 0.4.0

p

passport.authenticate: AuthenticateOptions missing loginHint.
How to pass login_hint = "xyz"

SessionStrategy never calls success.

My understanding is that SerializeUser is called once to setup the cookie, it stores the session id in the cookie, and user details in the session. On subsequent invocation it uses the cookie to extract the session and then calls deserialize user. So the expected sequence would be SerializeUser DeserializeUser DeserializeUser ( and so on , until the session times out ). But I am having additional SerializeUser interspersed between DeserializeUsers.
I investigated why this maybe. When we ask for authenticate, passport cycles through its strategies. Each strategy can either respond one of the following: success, fail, pass or error. If its success, it won't try the next strategy. This issue here is that the Session Strategy responds with pass even though it was able to successfully deserialize the user. The passport authenticator then attempts to do the next strategy which is the facebook auth, which causes SerializeUser to happen and we reauthenticate with facebook which is what I wanted to prevent by using SessionStrategy. I fail to understand why the SessionStrategy did not immediately respond with Success and stop passport from exploring the following strategies.

Set cookie in strategy

I would like to implement a custom strategy which sets a cookie on the response, but custom strategies do not appear to have access to the response object. Is there an appropriate way to do this?

My authentication is initially via google oauth2, with the id_token then validated using an internal authentication and authorisation service. That service provides me with a token to use to authenticate subsequent requests, and a refresh token to generate new tokens when that token expires.

The oauth2 strategy also doesn't allow me to set a cookie directly, so the route handler for the oauth callback route sets the cookie instead.

This a viable (if daft) workaround for the other routes that use the cookie/token auth strategy I want to implement - add another bit of middleware that just sets the cookie based on the extracted user.

Is there a better way to manage this?

Impossible to connect when using jwt

Hi,
I want to use jwt rather than session. But endpoint metioned in documentation:

app.get('/connect/twitter',
  passport.authorize('twitter-authz', { failureRedirect: '/account' })
);

can be reached only by redirection using <a href='/connect/twitter'>, XMLHttpRequest is not possible due to CORS error (it will automatically attempt to redirect the browser to the strategy's service). So I cant send token to server, user data encoded in token cant be reached, and so new social user data cant be merged and saved into database. In conslusion, social connections can be done only using session on server.

Can I dynamically configure strategy per-domain?

Hello, I want to use different credentials and callback url for PassportJS strategies, based on the current domain. I want to use this so that I can use one application serving multiple domains, with different social applications.

Is this possible?

Thanks!
Bahadir

Callback Endpoint vs Verify Calllback in Strategy

For an OAUTH2 Strategy (Auth0)
I discovered that there are two mentions of callback which is :

  • 1 Callback url
  • 2 Verify Callback defined in the strategy

Can they co-exist, if yes, what should be done in either of the 2

How do I login to a users account when handling support tickets?

I'm using 'passport-local' and 'passport-local-mongoose' to handle my users account authentication. I'm looking for an easy way to access my user's accounts (log in as if I were them) to see what issues they are having and help them fix them.

Currently what I do is copy a known hash and salt to their account, then log in to their account, and then put back their original hash and salt but that's time-consuming and I'm sure there is a better way.

How do I access my user's accounts without manually replacing the hash and salt in the DB?

The req.user objected is empty. Hitting Route Using Postman

Github Link : https://github.com/StackBeans/Review-App
I can't access req.user when i send get/post or any call from Postman in localhost env. I want to build REST API using Postman. Its working fine in browser.

router.get("/facebook", passport.authenticate("facebook"));
router.get(
  "/facebook/callback",
  passport.authenticate("facebook", {
    successRedirect: "/api/auth/current",
    failureRedirect: "/api/auth/facebook",
  })
);

The /current route is just sending res.send(req.user)

router.get("/current", userCtrl.getUserInfo);

 //getUserInfo(req, res) {
 //   if (req.user) res.send(req.user);
//    else res.send({ error: "req.user not found" });
//  }

What should i do to get req.user when making call API using Postman. Please help me out. I am stuck.

Where does passport look to serialize/ deserialize the user / what does it need.

I am sending a req with a session cookie & session id (req.session.cookie & req.sessionID), but I can't exchange the session id for user information. I've added the passport authenticate middleware on the route that should retrieve the user.
Logging in works, the user gets saved to the database and a session is created in the session store, but I can't seem to get the user information.

Authentication Issues on Safari/Chrome/Opera & potentially more

Hello,
I've been using essentially the exact same implementation as the one seen at http://www.passportjs.org/docs/authenticate/ for my site for some time now. Recently it has started to fail to authenticate users on Safari, Chrome, and Opera... I assume other Chromium-based browsers are affected as well. Signing in is working fine on Firefox, Samsung Internet and facebook's built in browser.

Using the problematic browsers, req is undefined after calling passport.authenticate('local').

Single login

How to do a single login with passport-local?

Authenticated user with Passport breaks static file serving

Below, when a user is not authenticated - "AFTER STATIC" does not appear, and the static file is served as expected.

When a user is logged in - "AFTER STATIC" appears, the user is served the file and a 404 error.

app.use(lessMiddleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next) {
  console.log("AFTER STATIC");
  return next();
});

PKCE id_token validation via passportjs help

Hi all,

I've tried to configure a few different strategies and tried sending an id_token in various ways but I'm unable to get any response.

I am using AppAuth via Expo which returns a json object with idToken and the other expect values. I've tried sending the idToken a POST parameter and and in the header but passport doesn't respond in anyway.

Is there a good way to get debug info from passport? Or can someone tell me how I should be sending the oauth response to passport?

Thank you!

req.login() doesn't save the session - Express V4

I'm trying to force the login of a user using a token on an express.js app. The problem is that even if the req.login() doesn't fire any error, the user session is not saved. Here my code:
https://hastebin.com/palaqemega.js

And here is how I configured the app:
https://hastebin.com/omaqiyalez.php

The table containing the user information is Utente (the Italian for User). I also tried manually setting the session by doing req.session = result[0] but it didn't work.

Unexpected redirect when using Google oauth2

Hey everyone,
I used passport on my node.js server. I'm trying to authenticate my users via Google's oauth2.
The authentication process is as follows:

  1. User is redirected to <server>/auth/google, which uses passport's middleware thus:
    passport.authenticate("google", { scope: ["profile", "email"] })
  2. User receives Google's login page and logins
  3. Google redirects user to <server>/auth/google/callback, which uses passport's middleware thus:
    passport.authenticate("google", { failureRedirect: "/", session: false })
  4. User is redirected to <client>?token=<token>

I am hosting my project's front-end on Netlify and the back-end on NOW.
Everything works when running local, yet when running in production there is an unexpected redirect during step 3, in which the user is redirected to <server>/auth/google/t?token=<long-token-string> instead of the path mentioned.

What causes this? Any ideas?
Thanks,
Ofek

Sign in as user and sign in as organization

Hi, I am building an app which requires register and login for user as well as org. I am using node js passport - local strategy for the same.

Here is my app.js file
Screenshot from 2020-06-08 01-20-14

Here is my passport.js file
Screenshot from 2020-06-08 01-24-21

Here is my post request for login form.
Screenshot from 2020-06-08 01-25-41

I am able to login with user but not with organization?

Verify Callback required

I followed the example for setting up and using passport-twitter at passport-twitter example. Although, I'm using normal HTML. I've checked the rest of the stuff and it there is no problem with it. But I'm still getting this error. Can anyone tell me what might this be?
error

Backwards-compatibility with Meteor Accounts?

Sorry if this seems like a basic question, I still know very little about how Passport works.

But basically I have an existing Meteor app storing accounts info in a Mongo database according to Meteor's own guidelines, and I'm wondering how to switch to Passport while preserving backwards compatibility?

Is there a way to tell Passport to store its own data following the same structure that Meteor is already using? Or should I instead run a one-time migration to port the Meteor accounts data to Passport's own preferred structure?

Has anybody worked on implementing either one before?

500 TypeError: this.fail is not a function

I've build a basic loopback4 application with authentication via passport-http module like described in this https://github.com/strongloop/loopback-next/tree/master/packages/authentication#loopbackauthentication documentation.
For each request with auth i receive the following error:

Unhandled error in GET /whoami: 500 TypeError: this.fail is not a function
at BasicStrategy.authenticate (/home/node/app/node_modules/passport-http/lib/passport-http/strategies/basic.js:69:37)
at AuthenticateActionProvider.action (/home/node/app/node_modules/@loopback/authentication/dist/providers/auth-action.provider.js:55:44)
at process._tickCallback (internal/process/next_tick.js:68:7)

Tried to investigate the code but couldn't figure out where this function should come from.
Any hints on this ?

New strategy globaliD

Hello,

I was trying to implement globaliD login with default passport-oauth2 strategy. Unfortunately it always uses response_type=code instead of response_type=token.

There is already a related post to find here

I am not able to create this strategy by myself, so I was hoping that someone from the community could help me out here.

Here is the globaliD documentation

And here is my example application showing a basic globaliD authentication process in comparison to some other social logins like twitter and github.

Thanks a lot and best regards,

Chris

How do I Identify what authenticator validated my request.

I have my server set up to pull from either a session (provided in the cookie) or from the JWT. I also have totp set up.

The issue is I want to enforce totp for all cookie sessions, but for jwt sessions (generally meaning another service is making the request) it would probably not be necessary.

How do I differentiate between the two. Is there some way to modify the session via the Strategy callback?

Error: Response for preflight requests are invalid.

We are trying to use passportjs for authenticating using ADFS. However, an error is thrown despite adding cors to our requests. Added both the server code and client code. The server code is also available here.

auth0/node-jsonwebtoken#59

Server - Code

index.js
`'use strict';

// N.B. Encoding problems are being caused by jsonwebtoken
// auth0/node-jsonwebtoken#59

var app = require('express')(),
cookieParser = require('cookie-parser'),
jwt = require('jsonwebtoken'),
passport = require('passport'),
OAuth2Strategy = require('passport-oauth').OAuth2Strategy,
fs = require('fs');

var cors = require('cors');
var https = require('https');
console.warn('Not verifying HTTPS certificates');
https.globalAgent.options.rejectUnauthorized = false;

// Exported from ADFS

var adfsSigningPublicKey = fs.readFileSync('ADFS-Signing.cer','utf8');

var cert = convertCertificate(adfsSigningPublicKey);

function validateAccessToken(accessToken) {
var payload = null;
try {
payload = jwt.verify(accessToken, cert,{algorithms: ["HS256"], ignoreExpiration: true});
}
catch(e) {
console.warn('Dropping unverified accessToken', e);
}
return payload;
}

function convertCertificate (cert) {
//Certificate must be in this specific format or else the function won't accept it
var beginCert = "-----BEGIN CERTIFICATE-----";
var endCert = "-----END CERTIFICATE-----";

cert = cert.replace("\n", "");
cert = cert.replace(beginCert, "");
cert = cert.replace(endCert, "");

var result = beginCert;
while (cert.length > 0) {

    if (cert.length > 64) {
        result += "\n" + cert.substring(0, 64);
        cert = cert.substring(64, cert.length);
    }
    else {
        result += "\n" + cert;
        cert = "";
    }
}

if (result[result.length ] != "\n")
    result += "\n";
result += endCert + "\n";
return result;

}

// Configure passport to integrate with ADFS
var strategy = new OAuth2Strategy({
authorizationURL: 'https://sso.xxx.com/adfs/oauth2/authorize',
tokenURL: 'https://sso.xxx.com/adfs/oauth2/token',
clientID: 'xxxxxxxx-xxxx-xxxx-xxxx-0cxxx4489fa', // This is just a UID I generated and registered
clientSecret: 'shhh-its-a-secret', // This is ignored but required by the OAuth2Strategy
callbackURL: 'http://localhost:3000/getAToken'
},
function(accessToken, refreshToken, profile, done) {
if (refreshToken) {
console.log('Received but ignoring refreshToken (truncated)', refreshToken.substr(0, 25));
} else {
console.log('No refreshToken received');
}
console.log("done ** " + profile);
done(null, profile);
});
strategy.authorizationParams = function(options) {
return {
resource: 'icebergdev' // An identifier corresponding to the RPT
};
};
strategy.userProfile = function(accessToken, done) {
done(null, accessToken);
};
passport.use('provider', strategy);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});

// Configure express app
app.use(cookieParser());
app.use(cors());
app.use(passport.initialize());
// app.options('*', cors());
app.use(function(req, res, next) {
// res.header('Content-type', 'text/plain')
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Methods', 'GET,POST');

//res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' == req.method) {
     res.send(200);
 } else {
     next();
 }
});

app.get('/login', passport.authenticate('provider'),function(req, res) {
// Beware XSRF...
// res.json({ message: "ok", token: req.user });
});
app.get('/getAToken', passport.authenticate('provider'), function(req, res) {
// Beware XSRF...
console.log("*********************************");
res.cookie('accessToken', req.user);
res.redirect('/');
//res.json({ message: "ok", token: req.user });
});
app.get('/', function (req, res) {
console.log('default is called');
req.user = validateAccessToken(req.cookies['accessToken']);
res.send(
!req.user ? 'Log In' : 'Log Out' +
'

' + JSON.stringify(req.user, null, 2) + '
');
});
// app.get('/logout',cors(), function (req, res) {
// res.clearCookie('accessToken');
// res.redirect('/');
// });

app.listen(3000);
console.log('Express server started on port 3000');`

and in my client code I am using the following to call my request.

`const params = {
method: 'GET',
headers: {

                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Methods": "GET, POST",
                    "Access-Control-Allow-Headers": "Content-type",
                    "Access-Control-Allow-Credentials": true,
                },
                withCredentials: true
            }

            axios('/login', params)
            .then(response => {
                response.data;
            })
            .catch(error => {
                debugger;
                console.log('error');
            })`

Invalid X-Requested-With header using Okta Identity Strategy

I am using Istio as an ingress gateway and trying to setup okta within a sidecar proxy but keep running into a 'Invalid X-Requested-With header' error. istio holds the self-signed cert to my app https://myapp.com that gateway has mTLS enabled to my service via TCP 7000 which then communicates with a nodejs app using http://www.passportjs.org/packages/passport-okta-oauth/

Okta is setup as follows:

Login redirect: https://myapp.com/api/auth/okta/handler/frame
Logout: https://myapp.com/api/auth/okta/logout
Initiate Login: https://myapp.com/api/auth/okta/start

App logs:
GET https://myapp.com/api/auth/okta/refresh?optional&env=development
GET https://myapp.com/api/auth/okta/start?scope=openid%20email%20profile%20offline_access&env=development

App Setup:
clientId/clientSecret/audience is set to https://my-domain.oktapreview.com

Front end error to user who has access is: Authentication failed, Failed to obtain access token
Front end error to user who does not have access: Authentication rejected, User is not assigned to the client application

Can I change the Strategy parameters at run-time?

Hello, I want to use a different cliendID, clientSecret and callback URL at run-time, e.g. per-request based on the "HOST" header.

I understand I can create a different strategy for each, but that is overkill, since I want to keep everything about the strategy the same, except the input parameters.

Is this possible, and even if not, can you suggest a decent shortcut? I am happy implementing temporary hacks :)

Thanks!
Bahadir

Passport returns unauthorized without error message

Not sure if this is a bug or a misuse of the lib but I cannot manage to get proper error messaging from passport.js

import express from 'express';
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';

const app = express();
const port = 8000;

// Middlewares
app.use(passport.initialize());

// Configure authetication
passport.use(new LocalStrategy({
  usernameField: 'username',
  passwordField: 'password'
}, (username, password, done) => {
  console.log('This actually prints on console on a POST request');
  return done(null, false, { message: 'this message never shows up' });
}));

app.post('/login', passport.authenticate('local'));

app.listen(
  port,
  () => log(`Server is running on http://localhost:${port}`)
);

Am I forgetting something here ? Any help is welcome. This is not blocking as it returns unauthorized headers but I'd like to have a feedback on why precisely the user is unauthorized like the docs indicate.

Passport doesn't set the req.user while testing with Supertest, using cookieSession

Hey!

I have an issue testing the Express app with Supertest, using the 'cookieSession' from Express.
Everything works fine, when I use session from Express, but cookieSession just obviously doesn't send cookies correctly or something.
I am using PassportJS to authenticate the user and set the user to request object (req.user). So the /login works as expected, it returns the right set-cookie header, but on the next request, the authentication fails, which doesn't set the req.user property with the user object.

Versions:

  • Express: 4.16.2
  • PassportJS: 0.3.2
  • Supertest: 2.0.1
  • Superagent: 2.3.0
  1. This is how I initialize the superagent:
import * as supertest from 'supertest';
import * as superagent from 'superagent';
import app from '../../app';
const request = supertest.agent(app);
  1. I run login before the tests (using async/await feature):
await request.post('/login').send({
  email: '[email protected]',
  password: 'plainpassword'
});
  1. Then I make first request to the backend for retrieving data:
const readResponse: superagent.Response = await request.post('/getData').send(requestBody);

And this is where it fails. It returns me the status code 401, beacuse PassportJS can not find the user ID in the cookie.

In the app.ts I set the cookieSession and passportJS session like that:

app.use(cookieSession({
  keys: [process.env.SESSION_SECRET],
  maxAge: 24 * 60 * 60 * 1000 * 14 // 14 days
}));
app.use(passport.initialize());
app.use(passport.session());

BUT: If I use the normal session (which is storing data in the database):

app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  cookie : {
    expires: false
  },
  store: new MongoStore({
    url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());

then everything works like a charm.

Can you treat this as a bug or am I missing something?

Thanks!

LocalStrategy verify function is never executed

I'm trying to use passport local with nextjs. But I don't know why, the verify function of LocalStrategy is never executed and the login just fail (I get back to the login page). I have the following form:

<form method='post' action='/login'>
	<input type='text' name='username' />
	<input type='text' name='password' />
	<button type='submit'>Login</button>
</form>

and there is the server.js:

require('dotenv').config()
const next = require('next')
const express = require('express')
const session = require('express-session')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const uid = require('uid-safe')

const dev = process.env.NODE_ENV !== 'production'
const app = next({
  dev,
  dir: './src'
})

const nextHandle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()
  const sessionConfig = {
    secret: uid.sync(18),
    cookie: {
      maxAge: 86400 * 1000 // 24 hours in milliseconds
    },
    resave: false,
    saveUninitialized: true
  }
  server.use(session(sessionConfig))

  passport.use(new LocalStrategy(function(username, password, done) {
    console.log(`login ${username}:${password}`) // This is never executed
    if (username === process.env.USERNAME && password === process.env.PASSWORD)
      return done(null, {username})
    done(null, false)
  }))
  passport.serializeUser((user, done) => done(null, user))
  passport.deserializeUser((user, done) => done(null, user))
  server.use(passport.initialize())
  server.use(passport.session())

  server.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }), (req, res) => {
    res.redirect('/')
  })
  server.get('*', nextHandle)

  server.listen(process.env.PORT)
})

Passport and React Native

Hi, I'm trying to create a react native app with node express backend and the passport-steam strategy.

When the user in the app click on the login button a browser with the authentication page pop out and let the user log in normally. Then the user is redirected back on the app using deep-links but when I try to perform a GET request to get back the req.user it doesn't return anything. This code is perfectly running on desktop browser but I can't manage to let it work on react native.

I strongly believe that this is led by the fact that React Native is not a browser environment and so I need to manage session cookies on my own.

Can somebody explain me how to do this thing and maybe link some guides or some useful GitHub repos.

Thank in Advance

passport.use is not a function

Hi,
I'm getting the above error after renaming my .babelrc file as babel.config.js and adding: module.exports={...same configuration...}.
importing passport as const passport = require('passport'); resolve in an empty object.

Many thanks,

Problems when using oAuth 2.0 with Google and Facebook

In my web app, I starting using oAuth 2.0 with google and it worked. So I decded to also use oAuth 2.0 with Facebook. There is one problem though; it doesn't work if I use oAuth 2.0 with google So if a user registers using google, his information will be stored in the database. However if another user registers using facebook, it will throw an error. The only way to fix this error is to clear the database. When I do, it works for facebook, but this time oAuth 2.0 using google doesn't work. It throws the same error:
MongoError: E11000 duplicate key error collection: usersDB.users index: username_1 dup key: { username: null }

FacebookGraphAPIError: (#210) This call requires a Page access token

I am using Passport-Facebook strategy for authentication. Please find the code below:

new FacebookStrategy(
      {
        clientID: authConfig.facebookAuth.clientID,
        clientSecret: authConfig.facebookAuth.clientSecret,
        callbackURL: authConfig.facebookAuth.callbackURL,
        profileURL: "https://graph.facebook.com/v2.10/me",
        authorizationURL: "https://www.facebook.com/v2.10/dialog/oauth",
        tokenURL: "https://graph.facebook.com/v2.10/oauth/access_token",
        profileFields: ["email", "profile_pic", "gender"]
      },
      function(accessToken, refreshToken, profile, done) {

This is giving me the following error:

FacebookGraphAPIError: (#210) This call requires a Page access token.
How do I pass the page access token? Or is this related to something else?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.