Home >Web Front-end >JS Tutorial >Using Passport to provide social authentication for Node.js applications

Using Passport to provide social authentication for Node.js applications

WBOY
WBOYOriginal
2023-09-01 20:41:071257browse

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