I'm using passport.js to authenticate users. I would like to be able to pass a username, collected from the user, which will reach the end of the authentication process so that I can store the username when I create the user (if it doesn't yet exist). I've tried this:
app.get("/auth/google", function(request, response)
{
console.log(request.query.username);
passport.authenticate("google",
{
scope:
[
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email"
]
})(request, response);
});
app.get("/auth/google/callback", function(request, response)
{
console.log(request.query.username);
passport.authenticate("google",
{
successRedirect: "/",
failureRedirect: "htm/error"
})(request, response);
});
The call to /auth/google prints the username, but the callback prints undefined. Even if I could get the username to the callback, I'm still not sure how I would get it to the google strategy. Would I then have to create my own strategy to get this to work?
You can use the request itself to transfer some additional parameters from and to the strategy function. In the following example the two parameters _toParam and _fromParam are used for this concern. app. get('/auth/facebook/:appId', function(req,res,next){ req.
The “Passport JS” library connects with the “expression-session” library, and forms the basic scaffolding to attach the (authenticated) user information to the req. session object. The main Passport JS library deals with already authenticated users, and does not play any part in actually authenticating the users.
Strategies are responsible for authenticating requests, which they accomplish by implementing an authentication mechanism. Authentication mechanisms define how to encode a credential, such as a password or an assertion from an identity provider (IdP), in a request.
Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.
You can pass a state object to passport.authenticate, like so:
passport.authenticate("google",
{
scope:
[
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email"
],
state: request.query.username
})(request, response);
You can access the state through req.query.state.
The username should be a string, not an object. If you want to store an object in the state, call JSON.stringify before and parse it in the callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With