loading...
Cover image for Facebook Auth ( Node.js and Passport.js )

Facebook Auth ( Node.js and Passport.js )

mkilmer profile image MKilmer Updated on ・2 min read

In this week, i learned about auth with social networks ( in this case, auth with Facebook ). I created a simple API with Node.js and Passport.js ( auth API ). So, let's code !

Passport.js
Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

Before code, is necessary make some configurations - get API key in Facebook Developers. I found a video explaining how to make the settings : https://www.youtube.com/watch?v=_hF099c0A9M

passes as body in the request json: (use Postman/Insomia)


{
 "access_token": "YOUR ACCESS TOKEN IN FACEBOOK DEVELOPER"
}

required dependencies


"dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^8.1.0",
    "express": "^4.17.1",
    "express-jwt": "^5.3.1",
    "passport": "^0.4.0",
    "passport-facebook": "^3.0.0",
    "passport-facebook-token": "^3.3.0",
    "mongoose": "^5.7.1"
  }

project structure

├── index.js 
├── passport.js 
└── app
 └── routes.js
 └── models
    └── user.js
└── .env

index.js

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();
const app = express();

// allow your application to be consumed
app.use(cors());

// mongodb local 
mongoose.connect(process.env.MONGODB_URL_DEV, {
    useUnifiedTopology: true ,
    useNewUrlParser : true
})

app.listen(3333, () => console.log('server on !'))

.env

MONGODB_URL_DEV=mongodb://localhost:27017/YOUR_NAME_PROJECT
PRIVATE_KEY=YOUR_KEY_PRIVATE
clientID=YOUR_CLIENT_ID
clientSecret=YOUR_CLIENT_SECRET

└── models
└── user.js

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    name : String,
    facebook_id : String,
    email: String,

});

module.exports = mongoose.model('AuthFacebook',UserSchema);

passport.js

const passport = require('passport');
const FacebookTokenStrategy = require('passport-facebook-token');
const User = require('./app/models/user');
require('dotenv').config();

passport.use('facebookToken', new FacebookTokenStrategy({
    clientID: process.env.clientID,
    clientSecret:process.env.clientSecret
}, async (accessToken, refreshToken, profile, done) => {
    try {
        if( await User.findOne({'facebook_id':profile.id})) return console.log('this account is already registered!')
        const email = profile.emails[0].value;
        const { id: facebook_id, displayName: name } = profile;
        const user = await User.create({
            email,facebook_id,name
        })
        await user.save();

        console.log(user)
    }catch(error){
        done(error,false,error.message)
    }
}));

routes.js

const express = require('express');
const router = new express.Router;

router.post('/user/signin/facebook',passport.authenticate('facebookToken',{session:false}))

module.exports = router;

SEE THE RESULT
Alt Text

Posted on by:

mkilmer profile

MKilmer

@mkilmer

Web and Mobile Development enthusiast, focusing on Javascript (Node.js, React and React Native). In your spare time, why not solve a Magic Cube?

Discussion

markdown guide
 

hello, i cannot res token while login with facebook

 

hello can u explain me how to get access token automatic?

 
 

hi, this line is wrong i guess "router.post('/user/signin/facebook',passport.authenticate('facebookToken',{session:false}))
"