strongloop / loopback-example-passport

LoopBack example for facebook login
Other
185 stars 134 forks source link

Loopback facebook Passport Error Login : FacebookAuthorizationError #115

Closed trungdh closed 5 years ago

trungdh commented 5 years ago

I'm trying to use Loopback Component Passport to allow users login via Facebook. But I got an error when redirect users to auth Facebook page

Login error: An error occurred while helping you log in to this application. Please try again later.

And Press OK button I got Error Log on my callback URL :

FacebookAuthorizationError 500 Login error: There was an error while helping you log in to this application. Please try again later. code : 1349003 status : 500 FacebookAuthorizationError: Login error: An error occurred while helping you log in to this application. Please try again later. at Strategy.authenticate (/root/server/node_modules/passport-facebook/lib/strategy.js:81:23) at attempt (/root/server/node_modules/passport/lib/middleware/authenticate.js:361:16) at authenticate (/root/server/node_modules/passport/lib/middleware/authenticate.js:362:7) at defaultCallback (/root/server/node_modules/loopback-component-passport/lib/passport-configurator.js:604:7) at Layer.handle [as handle_request] (/root/server/node_modules/express/lib/router/layer.js:95) at next (/root/server/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/root/server/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/root/server/node_modules/express/lib/router/layer.js:95) at /root/server/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/root/server/node_modules/express/lib/router/index.js:335:12) at next (/root/server/node_modules/express/lib/router/index.js:275:10) at SendStream.error (/root/server/node_modules/serve-static/index.js:121:7) at emitOne (events.js: 116: 13) at SendStream.emit (events.js: 211: 7) at SendStream.error (/root/server/node_modules/send/index.js:270:17) at SendStream.onStatError (/root/server/node_modules/send/index.js:421:12)

Here is What I tried :

  1. Configure Provider json to load for Passport Configuration

"facebook-login": { "provider": "facebook", "module": "passport-facebook", "clientID": "my facebook client ID", "clientSecret": "client secret", "callbackURL": "https://my_server_domain:6002/api/users/auth/facebook/callback", "authPath": "/auth/facebook", "callbackPath": "/api/users/auth/facebook/callback", "successRedirect": "/api/users/auth/account", "failureRedirect": "/api/users/signin", "scope": [ "emails" ], "failureFlash": true }, "facebook-link": { "provider": "facebook", "module": "passport-facebook", "clientID": "my facebook client ID", "clientSecret": "my client secret", "callbackURL": "https://my_server_domain:6002/api/users/link/facebook/callback", "authPath": "/link/facebook", "callbackPath": "/api/users/link/facebook/callback", "successRedirect": "/auth/account", "failureRedirect": "/api/users/signin", "scope": [ "email", "user_likes" ], "link": true, "failureFlash": true }

  1. Load it to Passport in Server.js

'use strict'; var loopback = require('loopback'); var boot = require('loopback-boot'); var path = require('path'); var app = module.exports = loopback(); var bodyParser = require('body-parser'); var session = require('express-session'); var cookieParser = require('cookie-parser'); var flash = require('express-flash'); var httpolyglot = require('httpolyglot'); var sslConfig = require('./ssl-config'); var http = require('http'); var https = require('https'); //create an instance of PassportConfigurator with the app instance const PassportConfigurator = require('loopback-component-passport').PassportConfigurator; const passportConfigurator = new PassportConfigurator(app); app.middleware('initial', bodyParser.urlencoded({ extended: true })); app.use('/express-status', function (req, res, next) { res.json({ running: true }); }); //custom access token model app.use(loopback.token({ model : app.models.AccessTokens, currentUserLiteral : 'me' })) app.set('view engine', 'html'); app.set('views',dirname + '/views'); //to support JSON encoded bodies app.middleware('parse', bodyParser.json()); // to support URL-encoded bodies app.middleware('parse', bodyParser.urlencoded({ extended: true })); //enable http session app.middleware('session:before',cookieParser('mysecret')); app.middleware('session',session({ secret : 'secret', saveUninitialized : true, resave : true })) //load the provider configurations var config = {}; try{ config = require('../provider.json'); }catch(err){ console.error('please configure your passport strategy in provider.json'); console.trace(err); process.exit(1); } //Initialize passport passportConfigurator.init(); // We need flash messages to see passport errors app.use(flash()); app.start = function(httpOnly) { //Get the FQPN of the index file in client var staticFolder = path.dirname( path.resolve(dirname,'..', app.get('indexFile')) ); //set static folder as static in server app.use(loopback.static(staticFolder)); passportConfigurator.setupModels({ userModel: app.models.Users, userIdentityModel: app.models.userIdentity, userCredentialModel: app.models.userCredential, }) for (var s in config) { var c = config[s]; c.session = c.session !== false; //override to custom profileToUser function c.profileToUser = function(provider,profile, options){ let email = profile.emails && profile.emails[0] && profile.emails[0].value; let name = profile.displayName || profile.name.familyName + profile.name.givenName; let password = profile.id; let image_profile = profile.photos && profile.photos[0] && profile.photos[0].value; var userObj = { is_third_party : true, name : name, password : password, emailVerified : true }; if(email){ userObj.email = email; } if(image_profile){ userObj.image_profile = image_profile } return userObj; } passportConfigurator.configureProvider(s, c); } // start the web server return app.listen(function() { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); console.log('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; console.log('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err; // start the server if $ node server.js if (require.main === module) app.start(); });

  1. Handle callback in Users.js model

Users.authFacebookCallback = (req,res,next)=>{ console.log('google callback with user info ', req); next(); } //auth with third party successed Users.authAccount = (req,res,next)=>{ console.log('third party account with user info ', req.user); let user = req.user; let response = { user : user } //mapping Customer role for users logged in Users.app.models.Role.findOne({where : {name : 'customer'}}) .then(customer_role=>{ return customer_role }).then(role=>{ return Users.app.models.RoleMapping.create({ principalType : Users.app.models.RoleMapping.USER, principalId : user.id.toString(), roleId : role.id }).then(roleMapping=>{ console.log('mapping customer for users logged in with third party success ',roleMapping); return role; }).then(role=>{ user.accessTokens.find().then(accessToken=>{ response.access_token = accessToken; response.user.roles = [role.name]; next(null, response); }).catch(err=>{ next(err); }) }).catch(err=>{ next(err); }) })

  1. I've configured my domain and callback URL on Facebook developer But I alway get Facebook Authorization Error Login Error. What is I am missing in my code
stale[bot] commented 5 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] commented 5 years ago

This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.