I am trying to authorize a pre logged in user with a Facebook account. I want to store the auth token of Facebook to later post stuff using my CMS.
I am using Express/NodeJS and Passport JS.
My FacebookStrategy looks like this:
module.exports = new FacebookStrategy(
{
clientID,
clientSecret,
callbackURL: `${config.apiUrl}/v1/auth/connect/facebook/callback`,
passReqToCallback: true
},
async function(req, token, tokenSecret, profile, done) {
console.log("SESSION?", req.session)
console.log("THIS SHOULD BE SET!", req.user) // But is not!
// Stuff is done.
done(null, token, {savedConnectionForLaterUse});
}
I also have two routes:
router.get('/connect/facebook',
API_KEY_OR_JWT_AUTH_MIDDLEWARE,
(req, res, next) => {
// Save authInfo in session
Object.assign(req.session, {account: req.authInfo.account._id, user: req.user._id})
passport.authorize('facebookConnect', {
failureRedirect: `${frontUrl}/settings/connections`,
scope: facebookOAuthScopes, // This is an array of scopes I need
})(req, res, next)
},
);
router.get('/connect/facebook/callback',
passport.authorize('facebookConnect', {
failureRedirect: `${apiUrl}/v1/auth/connect/facebook/failure`,
}),
(req, res) => {
const { session: {connection} } = req;
res.redirect(`${frontUrl}/settings/connections/edit/${connection}`);
}
);
When I am running this on my local machine it works due to the fact that the session is there and in the session I can find my user for later use. As soon as I am deploying this on a server (with kubernetes) the session is gone.
The configuration of the express session looks like this:
app.use(
expressSession({
secret: config.security.secret,
resave: true,
saveUninitialized: true,
cookie: {
sameSite: 'none', // This was something I tried.. didn't help thou
secure: true,
},
})
)
Can anyone point me into the right direction? What am I doing wrong?
Thank you all for your help in advance. I am really at the end of my knowledge. The struggle is real! :D
Related
I am in a next-js app and my auth token is stored in cookies.
For some raisons i use Swr and Api route to fetch my secured api backend.
i am trying to find a way to put my auth token in all api request.
During login cookie is set
res.setHeader(
'Set-Cookie',
cookie.serialize('token', data.access_token, {
httpOnly: true,
secure: process.env.NODE_ENV !== 'development',
maxAge: data.expires_in, // 1 week
sameSite: 'strict',
path: '/',
}),
);
This is an example of a page using swr fetch
//page/test.ts - example of my test route
const { data, error } = useFetchContent(id);
if (error) {
showError('error');
replace('/');
}
return <DisplayContent content={data} />
This is a swrFetchHook
// fetchContentHook
function useFetchContent(id: string): ContentDetail {
return useSWR<any>(`/api/content/${id}`, fetcherApiRoute);
}
const fetcherApiRoute = (url: string): Promise<any> => {
return axios(url)
.then((r) => r.data)
.catch((err) => {
console.info('error is ', err)
throw err
});
};
export default useFetchContent;
inside api route
export default async (req, res): Promise<ContentDetail> => {
const { id } = req.query;
if (req.method === 'GET') {
const fetchRealApi = await apiAxios(url);
if(fetchRealApi) {
// here depending on result of fetchRealApi i add some other fetch ...
return res.status(200).json({ ...fetchRealApi, complement: comp1 });
}
return res.status(500)
}
return res.status(500).json({ message: 'Unsupported method only GET is allowed' });
};
and finally api axios configuration
const apiAxios = axios.create({
baseURL: '/myBase',
});
apiAxios.interceptors.request.use(
async (req) => {
// HERE i am trying to get token from cookies
// and also HERE if token is expired i am trying to refresh token
config.headers.Authorization = token;
req.headers['Content-type'] = 'application/x-www-form-urlencoded';
return req;
},
(error) => {
return Promise.reject(error);
},
);
export default apiAxios;
I am stuck here because i cant find token during apiAxios.interceptors.request.use...
Did you know what i am doing wrong, and am i on a correct way to handle this behavior ?
To allow sending server cookie to every subsequent request, you need to set withCredentials to true. here is the code.
const apiAxios = axios.create({
baseURL: '/myBase',
withCredentials: true,
});
Nilesh's answer is right if your API is able to authorize requests based on cookies. Also it needs the API to be in the same domain as your frontend app. If you need to send tokens to the API (the one which is in the cookie), then you will need a small backend component often called BFF or Token Handler. It can extract the token from the cookie and put in an Authorization header.
At Curity we've created a sample implementation of such a Token Handler, of which you can inspire: https://github.com/curityio/kong-bff-plugin/ You can also have a look at an overview article of the Token Handler pattern.
This is my first time posting a question up here. I hope you guys can help me out with this. I am fairly new to node.js, express, so sorry in advance for my inexperience.
I am currently having a problem with my authentication session in my node.js, express app. I use Passport.js to handle my authentication, I store the login session with connect-pg-simple (a PostgreSQL session store). After clicking the login button, the session was stored inside my PostgreSQL database, but somehow express couldn't find it. In fact, it stores the session twice in the database, but only one of them got the passport cookie in it.
This issue was not present when the server was still on localhost. It appears when I host my server on Heroku.
Also, whenever I push to heroku repo, it shows this warning:
"connect.session() MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process."
My guess is I didn't connect express session to the PostgreSQL express store properly. Below is my code:
This is how I set up the PostgreSQL database:
const Pool = require("pg").Pool;
const pool = new Pool({
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
host: process.env.PGHOST,
port: process.env.PGPORT,
database: process.env.PGDATABASE
});
module.exports = pool
This is how I set up the session:
const poolSession = new (require('connect-pg-simple')(session))({
pool : pool
})
app.set('trust proxy', 1);
app.use(session({
store: poolSession,
secret: process.env.SESSION_SECRET,
saveUninitialized: true,
resave: false,
cookie: {
secure: true,
maxAge: 30 * 24 * 60 * 60 * 1000
} // 30 days
}));
app.use(passport.initialize());
app.use(passport.session());
This is the image of 2 sessions were store in the database when clicking the login button
https://i.stack.imgur.com/lzAby.png
This is my login route (when click the login button):
router
.route("/signin")
.post((req, res, next) => {
console.log("Signing in...")
passport.authenticate('local', function(err, user, info) {
//code....
req.logIn(user, function(err) {[enter image description here][1]
console.log(user);
if (err) {
console.log(err);
res.send(apiResponse(500, err.message, false, null))
return next(err);
}
console.log(req.sessionID); //The id of the 1st session store in db
console.log(req.isAuthenticated()) //True
res.redirect('/auth');
});
})(req, res, next);
})
This is the route that is redirected to when login successfully:
router.get("/", (req, res) => {
console.log("/ ", req.isAuthenticated()); //False
console.log("/ ", req.sessionID); //The Id of the 2nd session store in db
if(req.isAuthenticated()){
//Notify user login success
}
});
I have been stuck here for a few days now. Please tell me if you need more code!
I'm trying to implement passport-openidconnect into my Sails app. I've installed sails-auth, passport, passport-local, passport-http, and passport-openidconnect, all of which are required to start the sails app. I copied the contents of this file to get a passport config since the sails app was already started when I began implementing. This is my config file so far:
module.exports.passport = {
openid_connect: {
name: 'OpenID Connect',
protocol: 'oauth2',
strategy: require('passport-openidconnect').OAuth2Strategy,
options: {
clientID: '',
clientSecret: ''
}
}
};
I based this off some of the default options that were in the config/passport.js file mentioned above.
I've searched for setup examples for the OpenID Connect, but haven't been able to find anything so far. Has anyone implemented this in their own project and could give me some pointers? Thanks!
I've implemented passport in sails, with passport-local, passport for Google/FB/Twitter, but without sails-auth !
I don't know passport-openID but this should be nearly the same.
First you need to add passport middleware like this in your config/http.js
Then you have to create the different strategy in config/passport.js (exemple with FacebookStrategy, it should
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, FacebookStrategy = require('passport-facebook').Strategy
var verifyExtHandler = function (token, tokenSecret, profile, done) {
checkAuthExt(profile, done);
};
var verifyHandler = function (mail, password, done) {
checkAuth(mail, password, done);
};
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function (user, done) {
user.password = null;
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object.
passport.use(new LocalStrategy({
usernameField: 'mail',
passwordField: 'password'
}, verifyHandler));
// Remplacer les 'XXXXX' par vos clés et 'yourhost.com' par votre nom de domaine
passport.use(new FacebookStrategy({
clientID: "XXXXXX",
clientSecret: "XXXXXX",
callbackURL: "http://yourhost.com/auth/facebook"
}, verifyExtHandler));
And you need to configure your routes (config/routes.js) :
'/auth/facebook': 'AuthController.facebook',
'/auth/facebook/callback': 'AuthController.facebook'
Then in your controller :
facebook: function (req, res) {
passport.authenticate('facebook', {
failureRedirect: '/auth/login'
}, function (err, user) {
if (err) {
return console.log(err);
}
req.logIn(user, function (err) {
if (err) {
console.log(err);
res.serverError();
return;
}
return res.redirect('/');
});
})(req, res);
}
Hope that helps !
I am using Meanjs.org boilerplate and Facebook Signup returns me to the Signup page.
Following are the steps that I have taken so far.
1) Setting up the Facebook App Site URL
http://localhost:3000/
and the callback URI of OAuth
http://localhost:3000/auth/facebook/callback
2) Placing the APP_ID and APP_Secret in as Client_ID and Client_Secret
facebook: {
clientID: process.env.FACEBOOK_ID || '*****',
clientSecret: process.env.FACEBOOK_SECRET || '*****',
callbackURL: 'http://localhost:3000/auth/facebook/callback',
profileFields: ['id','emails', 'first_name', 'last_name', 'displayName', 'link', 'about_me', 'photos' ]
},
3) Code is as follows
--Routes
// Setting the facebook oauth routes
app.route('/auth/facebook').get(passport.authenticate('facebook', {
scope: ['email']
}));
app.route('/auth/facebook/callback').get(users.oauthCallback('facebook'));
-- The oauthCallback function,
exports.oauthCallback = function(strategy) {
return function(req, res, next) {
passport.authenticate(strategy, function(err, user, redirectURL) {
if (err || !user) {
console.log('1' + err);
//console.log(user);
return res.redirect('/#!/signin');
}
req.login(user, function(err) {
if (err) {
console.log('2' + err);
return res.redirect('/#!/signin');
}
return res.redirect(redirectURL || '/');
});
})(req, res, next);
};
};
-- Passport-Facebook Strategy
module.exports = function() {
// Use facebook strategy
passport.use(new FacebookStrategy({
clientID: config.facebook.clientID,
clientSecret: config.facebook.clientSecret,
callbackURL: config.facebook.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
console.log('facebook Strategy Started');
// Set the provider data and include tokens
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
// console.log(JSON.stringify(profile));
console.log(profile);
// console.log(JSON.stringify(profile.name.givenName));
// Create the user OAuth profile
var providerUserProfile = {
firstName: profile.name.givenName,
lastName: profile.name.familyName,
displayName: profile.displayName,
email: profile.emails[0].value,
username: profile.username,
provider: 'facebook',
providerIdentifierField: 'id',
providerData: providerData
};
//console.log('provider' + providerUserProfile);
// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}
));
};
4) Debugging
Logging err under oauthCallback function returns the following,
1TypeError: Cannot read property '0' of undefined
What Facebook returns as profile in Passport-Facebook module is as follows,
{ id: 'Id_of_the_person',
username: undefined,
displayName: 'Full_name_of_person',
name:
{ familyName: undefined,
givenName: undefined,
middleName: undefined },
gender: undefined,
profileUrl: undefined,
provider: 'facebook',
_raw: '{"name":"Full_name_of_person","id":"Id_of_the_person"}',
_json:
{ name: 'Id_of_the_person',
id: 'Id_of_the_person',
accessToken: 'access_token_value',
refreshToken: undefined } }
Can anyone be kind to guide me about getting the correct user profile from Facebook including user email?
Thank you so much.
I have my profile fields set to the following
profileFields: ['email','id', 'first_name', 'gender', 'last_name', 'picture']
Even though you set email it might return emails if the user has multiple emails. So you need to check if email was returned profile.email or profile.emails[0].value. You must also check if it is undefined, because there is people that register with facebook that never verify their email account and there is people that sign up with a phone number, in both those cases their emails will always be undefined.
you want to check that any required fields have values.
var email = profile.email || profile.emails[0].value;
if (! email){
console.log('this user has no email in his FB');
var err = {message:'this user is missing an email'};
return done(err);
}
now i can do this if they have an email
newUser.facebook.email = email;
if they don't have an email you can set a session for profile and send them to a page that asks them to enter an email.
It sounds like a pain, but you can never trust information from a third party api to have values.
Most of the passport examples I've seen online are wrong. They all assume an email is present.
First, profileFields field does not obey to Portable Contacts convention - and you can find the convention for passportjs here.
Second, in your example, after removing removed 'about_me', the Facebook signup returns no error. Before removing 'about_me', I had a different error: Tried accessing nonexisting field (about_me) on node type (User)
If the error persist, see this serie of 5 tutorials which helps me when I was doing the sign up page to authenticate with social networks accounts.
In the example of oauth2 strategy usage in the Passport's repo, the following function is presented:
passport.use(new OAuth2Strategy({
authorizationURL: 'https://www.example.com/oauth2/authorize',
tokenURL: 'https://www.example.com/oauth2/token',
clientID: EXAMPLE_CLIENT_ID,
clientSecret: EXAMPLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/example/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ exampleId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
How does Passport obtains the profile field? is it provided with the token by the oauth endpoint? or does it come from a separate (session-related) request?
When using, for example, the Facebook's oauth API, the user info is loaded automatically with the Passport's Facebook strategy, so I'm trying to figure out how does this happen and how to implement a similar behavior in a custom oauth2 API.
The user profile is typically loaded after the access_token is successfully retrieved:
https://github.com/jaredhanson/passport-oauth2/blob/master/lib/strategy.js#L175
this._oauth2.getOAuthAccessToken(code, { grant_type: 'authorization_code', redirect_uri: callbackURL },
function(err, accessToken, refreshToken, params) {
if (err) { return self.error(self._createOAuthError('Failed to obtain access token', err)); }
self._loadUserProfile(accessToken, function(err, profile) {
if (err) { return self.error(err); }
The function to actually get the user information is often provided by the specific strategy (e.g. Facebook, Twitter, etc)
In Facebook's implementation:
https://github.com/jaredhanson/passport-facebook/blob/master/lib/strategy.js#L137