Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 inFacebook 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 modeExit 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 modeExit fullscreen mode

project structure

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

index.js

constexpress=require('express');constmongoose=require('mongoose');constcors=require('cors');require('dotenv').config();constapp=express();// allow your application to be consumedapp.use(cors());// mongodb localmongoose.connect(process.env.MONGODB_URL_DEV,{useUnifiedTopology:true,useNewUrlParser:true})app.listen(3333,()=>console.log('server on !'))
Enter fullscreen modeExit fullscreen mode

.env

MONGODB_URL_DEV=mongodb://localhost:27017/YOUR_NAME_PROJECTPRIVATE_KEY=YOUR_KEY_PRIVATEclientID=YOUR_CLIENT_IDclientSecret=YOUR_CLIENT_SECRET
Enter fullscreen modeExit fullscreen mode

└── models
└── user.js

constmongoose=require('mongoose');constUserSchema=newmongoose.Schema({name:String,facebook_id:String,email:String,});module.exports=mongoose.model('AuthFacebook',UserSchema);
Enter fullscreen modeExit fullscreen mode

passport.js

constpassport=require('passport');constFacebookTokenStrategy=require('passport-facebook-token');constUser=require('./app/models/user');require('dotenv').config();passport.use('facebookToken',newFacebookTokenStrategy({clientID:process.env.clientID,clientSecret:process.env.clientSecret},async(accessToken,refreshToken,profile,done)=>{try{if(awaitUser.findOne({'facebook_id':profile.id}))returnconsole.log('this account is already registered!')constemail=profile.emails[0].value;const{id:facebook_id,displayName:name}=profile;constuser=awaitUser.create({email,facebook_id,name})awaituser.save();console.log(user)}catch(error){done(error,false,error.message)}}));
Enter fullscreen modeExit fullscreen mode

routes.js

constexpress=require('express');constrouter=newexpress.Router;router.post('/user/signin/facebook',passport.authenticate('facebookToken',{session:false}))module.exports=router;
Enter fullscreen modeExit fullscreen mode

SEE THE RESULT
Alt Text

Top comments(4)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
mynguyen2010 profile image
mynguyen20-10
  • Joined

hello, i cannot res token while login with facebook

CollapseExpand
 
mzcoderhub profile image
Galang YP
  • Location
    Pekalongan
  • Work
    FullStack Developer at MzCoder-Hub
  • Joined

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

CollapseExpand
 
overtambrosio profile image
Overt Ambrosio Alcántara
  • Joined

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

CollapseExpand
 
themsiqueira profile image
Siqueira
Let's make the world a better place through technology!
  • Location
    Brazil
  • Education
    Unifesp - Universidade Federal de São Paulo
  • Work
    Software Engineer
  • Joined

Charlatonismo cantando

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

iOS Enginner. In your spare time, why not solve a Magic Cube?
  • Location
    Fortaleza,Ceará
  • Education
    IFCE - Computer Science Student
  • Joined

More fromMKilmer

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp