DEV Community

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

Posted on • Edited on

Facebook Auth ( Node.js and Passport.js )

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"
}

Enter fullscreen mode Exit fullscreen mode

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"
  }
Enter fullscreen mode Exit fullscreen mode

project structure

├── index.js 
├── passport.js 
└── app
 └── routes.js
 └── models
    └── user.js
└── .env
Enter fullscreen mode Exit fullscreen mode

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 !'))
Enter fullscreen mode Exit fullscreen mode

.env

MONGODB_URL_DEV=mongodb://localhost:27017/YOUR_NAME_PROJECT
PRIVATE_KEY=YOUR_KEY_PRIVATE
clientID=YOUR_CLIENT_ID
clientSecret=YOUR_CLIENT_SECRET
Enter fullscreen mode Exit fullscreen mode

└── 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);

Enter fullscreen mode Exit fullscreen mode

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)
    }
}));
Enter fullscreen mode Exit fullscreen mode

routes.js

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

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

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

SEE THE RESULT
Alt Text

Top comments (4)

Collapse
 
mzcoderhub profile image
Galang YP

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

Collapse
 
mynguyen2010 profile image
mynguyen20-10

hello, i cannot res token while login with facebook

Collapse
 
themsiqueira profile image
Siqueira

Charlatonismo cantando

Collapse
 
overtambrosio profile image
Overt Ambrosio Alcántara

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