search
HomeWeb Front-endJS TutorialUsing Passport to provide social authentication for Node.js applications

It is an accepted fact that passwords are inherently fragile. Therefore, requiring end users to create strong passwords for every application they use will only make matters worse.

A simple workaround is to have the user authenticate through an existing social account (e.g. Facebook, Twitter, Google, etc.). In this article, we are going to do just that and add this social login functionality to the first part of this authentication series so that we can authenticate with Facebook and Twitter accounts using the Passport middleware.

If you haven't read the previous article, I recommend you read it as we will be building on the foundation laid by this article to build new strategies, routes, and views.

Social Login

For the uninitiated, social login is a single sign-on that uses existing information from social networking sites like Facebook, Twitter, etc. The user should usually have already created an account.

Social login mainly relies on authentication schemes such as OAuth 2.0. To learn more about the different login flows supported by OAuth, read this article. We chose Passport to handle social login because it offers different modules for various OAuth providers, be it Facebook, Twitter, Google, GitHub, etc. In this article, we will use the Passport-facebook and Passport-twitter modules to provide login functionality through an existing Facebook or Twitter account.

Facebook Authentication

To enable Facebook Authentication, we first need to create a Facebook app using the Facebook Developer Portal. Make a note of the App ID and App Secret, then go to Settings and specify the Website URL in the Website section to specify the callback URL. application. Please also be sure to enter a valid email address in the Contact Email field. This application needs to be exposed and accessible to the public.

Next, go to the Status and Review section and turn the slider to Yes to make the app public. We create a configuration file fb.js to hold the configuration information needed to connect to Facebook.

// facebook app settings - fb.js
module.exports = {
  'appID' : '<your_app_identifier>',
  'appSecret' : '<your_app_secret>',
  'callbackUrl' : 'http://localhost:3000/login/facebook/callback'
}

Facebook Login Policy

Back to our Node application, we now define the Passport strategy for Facebook authentication using the FacebookStrategy module, leveraging the above settings to get the user's Facebook profile and display the details in a view.

passport.use('facebook', new FacebookStrategy({
  clientID        : fbConfig.appID,
  clientSecret    : fbConfig.appSecret,
  callbackURL     : fbConfig.callbackUrl
},

  // facebook will send back the tokens and profile
  function(access_token, refresh_token, profile, done) {
	// asynchronous
	process.nextTick(function() {
    
	  // find the user in the database based on their facebook id
	  User.findOne({ 'id' : profile.id }, function(err, user) {

	    // if there is an error, stop everything and return that
	    // ie an error connecting to the database
	    if (err)
	      return done(err);

		  // if the user is found, then log them in
	      if (user) {
	        return done(null, user); // user found, return that user
	      } else {
	        // if there is no user found with that facebook id, create them
	        var newUser = new User();

			// set all of the facebook information in our user model
	        newUser.fb.id    = profile.id; // set the users facebook id	                
	        newUser.fb.access_token = access_token; // we will save the token that facebook provides to the user	                
	        newUser.fb.firstName  = profile.name.givenName;
	        newUser.fb.lastName = profile.name.familyName; // look at the passport user profile to see how names are returned
	        newUser.fb.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first

			// save our user to the database
	        newUser.save(function(err) {
	          if (err)
	            throw err;

	          // if successful, return the new user
	          return done(null, newUser);
	        });
	     } 
	  });
    });
}));

Configure routing

Now we need to add some routes to enable Facebook login and handle the callback after the user authorizes the application to use their Facebook account.

// route for facebook authentication and login
// different scopes while logging in
router.get('/login/facebook', 
  passport.authenticate('facebook', { scope : 'email' }
));

// handle the callback after facebook has authenticated the user
router.get('/login/facebook/callback',
  passport.authenticate('facebook', {
    successRedirect : '/home',
	failureRedirect : '/'
  })
);

The login page for our demo application looks like this:

Using Passport to provide social authentication for Node.js applications

When you click the Log in with Facebook button, it will try to authenticate with Facebook. If you are already logged in to Facebook it will show the following dialog box asking for your permission otherwise it will ask you to log in to Facebook and then show this dialog box.

Using Passport to provide social authentication for Node.js applications

If you allow the app to receive your public profile and email address, then our registered callback function will be called with the user details. We can save this information for future reference, display it, or simply choose to ignore it, depending on what you want to do with it. Feel free to jump over and check out the full code in this git repository.

It is worth noting that in addition to the basic information provided by this demo application, you can also use the same authentication mechanism by using the appropriate scope and using the Facebook API with the access token received through the user profile.

Twitter Authentication

Needs to hook up a similar authentication module to handle authentication via Twitter, and plug in the Passport chip to help with its passport-twitter module.

First, you need to create a new Twitter application using its application management interface. One thing to note here is that when specifying a callback URL, Twitter doesn't seem to work well with "localhost" if you give it in the callback URL field. To overcome this limitation while developing, you can use a special loopback address or "127.0.0.1" instead of "localhost". After creating the application, note the following API key and secret information in the configuration file as shown below:

// twitter app settings - twitter.js
module.exports = {
    'apikey' : '<your_app_key>',
	'apisecret' : '<you_app_secret>',
	'callbackUrl' : 'http://127.0.0.1:3000/login/twitter/callback'
}

Twitter Login Policy

Twitter's login strategy is an instance of TwitterStrategy as follows:

passport.use('twitter', new TwitterStrategy({
    consumerKey     : twitterConfig.apikey,
    consumerSecret  : twitterConfig.apisecret,
    callbackURL     : twitterConfig.callbackURL
  },
  function(token, tokenSecret, profile, done) {
    // make the code asynchronous
    // User.findOne won't fire until we have all our data back from Twitter
    process.nextTick(function() { 

	  User.findOne({ 'twitter.id' : profile.id }, 
        function(err, user) {
          // if there is an error, stop everything and return that
		  // ie an error connecting to the database
	      if (err)
	        return done(err);

			// if the user is found then log them in
	        if (user) {
	           return done(null, user); // user found, return that user
	        } else {
	           // if there is no user, create them
	           var newUser                 = new User();

			   // set all of the user data that we need
	           newUser.twitter.id          = profile.id;
	           newUser.twitter.token       = token;
	           newUser.twitter.username = profile.username;
	           newUser.twitter.displayName = profile.displayName;
	           newUser.twitter.lastStatus = profile._json.status.text;

			   // save our user into the database
	           newUser.save(function(err) {
	             if (err)
	               throw err;
	             return done(null, newUser);
	           });
	        }
	     });
	  });
    })
);

配置路由

// route for twitter authentication and login
// different scopes while logging in
router.get('/login/twitter',  
  passport.authenticate('twitter')
);

// handle the callback after facebook has authenticated the user
router.get('/login/twitter/callback',
  passport.authenticate('twitter', {
	successRedirect : '/twitter',
	failureRedirect : '/'
  })
);

/* GET Twitter View Page */
router.get('/twitter', isAuthenticated, function(req, res){
  res.render('twitter', { user: req.user });
});

现在要对此进行测试,请务必使用 http://127.0.0.1:<port></port> 而不是使用 http: //localhost:<port></port>.正如我们上面已经提到的,在使用“localhost”作为主机名与 Twitter 交换令牌时似乎存在问题。单击使用 Twitter 登录按钮时,正如预期的那样,它会请求用户同意允许此应用程序使用 Twitter。

Using Passport to provide social authentication for Node.js applications

当您允许应用程序访问您的 Twitter 帐户和有限信息时,登录策略中注册的回调处理程序为调用,然后用于将这些详细信息存储在后端数据库中

结论

这就是你拥有的!我们成功地将 Facebook 和 Twitter 登录添加到示例应用程序中,而无需编写大量代码并通过让 Passport 完成繁重的工作来处理与身份验证机制相关的复杂问题。可以为 Passport 支持的各种提供程序编写类似的登录策略。整个应用程序的代码可以在此 git 存储库中找到。请随意扩展它并在您自己的项目中使用它。

The above is the detailed content of Using Passport to provide social authentication for Node.js applications. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment