首頁 > web前端 > js教程 > 主體

使用Passport為Node.js應用程式提供社交認證

WBOY
發布: 2023-09-01 20:41:07
原創
1213 人瀏覽過

密碼本質上是脆弱的,這已經是一個公認的事實。因此,要求最終用戶為他們使用的每個應用程式創建強密碼只會讓事情變得更糟。

一個簡單的解決方法是讓使用者透過現有的社群帳號(例如 Facebook、Twitter、Google 等)進行身份驗證。在本文中,我們將做到這一點,並將此社交登入功能添加到在這是本身份驗證系列的第一部分,以便我們能夠使用 Passport 中間件透過 Facebook 和 Twitter 帳戶進行身份驗證。

如果您還沒有閱讀過上一篇文章,我建議您閱讀它,因為我們將在這篇文章奠定的基礎上建立新的策略、路線和視圖。

社群登入

對於外行人來說,社交登錄是一種使用來自 Facebook、Twitter 等社交網站的現有資訊的單一登錄,用戶通常應該已經創建了帳戶。

社群登入主要依賴 OAuth 2.0 等身分驗證方案。要了解有關 OAuth 支援的不同登入流程的更多信息,請閱讀本文。我們選擇 Passport 來處理社交登錄,因為它為各種 OAuth 提供者提供了不同的模組,無論是 Facebook、Twitter、Google、GitHub 等。在本文中,我們將使用 Passport-facebook 和 Passport-twitter 模組透過現有的 Facebook 或 Twitter 帳戶提供登入功能。

Facebook 身份驗證

要啟用 Facebook 身份驗證,我們首先需要使用 Facebook 開發者入口網站建立 Facebook 應用程式。記下應用 ID 和應用程式金鑰,然後前往設定並在網站部分指定網站 URL,以指定回調 URL。應用。另請確保在聯絡電子郵件欄位中輸入有效的電子郵件地址。需要能夠公開此應用程式並可供公眾存取。

接下來,前往狀態和審核部分,並將滑桿轉到以使應用程式公開。我們建立一個設定檔 fb.js 來儲存連接到 Facebook 所需的設定資訊。

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

Facebook 登入策略

回到我們的 Node 應用程序,我們現在使用 FacebookStrategy 模組定義用於 Facebook 身份驗證的 Passport 策略,利用上述設定來獲取用戶的 Facebook 個人資料並在視圖中顯示詳細資訊。 < /p>

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);
	        });
	     } 
	  });
    });
}));
登入後複製

設定路由

現在我們需要添加某些路由,以啟用 Facebook 登入以及在用戶授權應用程式使用其 Facebook 帳戶後處理回調。

// 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 : '/'
  })
);
登入後複製

我們的示範應用程式的登入頁面如下所示:

使用Passport為Node.js應用程式提供社交認證

當您點擊使用 Facebook 登入按鈕時,它將嘗試透過 Facebook 進行身份驗證。如果您已經登入 Facebook,它將顯示以下對話框,請求您的許可,否則它將要求您登入 Facebook,然後顯示此對話框。

使用Passport為Node.js應用程式提供社交認證

如果您允許應用程式接收您的公開個人資料和電子郵件地址,那麼我們註冊的回呼函數將與使用者一起呼叫細節。我們可以保存這些資訊以供將來參考,或顯示它們,或者乾脆選擇忽略它們,這取決於您想要如何處理這些資訊。請隨時跳轉並查看此 git 儲存庫中的完整程式碼。

值得注意的是,除了此演示應用程式提供的基本資訊之外,您還可以使用相同的身份驗證機制透過使用適當的範圍並使用Facebook API 以及透過使用者個人資料收到的存取權杖。

Twitter 身份驗證

需要連接一個類似的身份驗證模組來透過 Twitter 處理身份驗證,並插入 Passport 晶片以幫助其 passport-twitter 模組。

首先,您需要使用其應用程式管理介面建立一個新的 Twitter 應用程式。這裡需要注意的一件事是,在指定回調 URL 時,如果在回調 URL 欄位中給出“localhost”,Twitter 似乎無法很好地使用它。為了在開發時克服此限制,您可以使用特殊的環回位址或「127.0.0.1」來取代「localhost」。建立應用程式後,在設定檔中記下以下 API 金鑰和機密信息,如下所示:

// 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 登入策略

Twitter 的登入策略是 TwitterStrategy 的實例,如下圖:

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。

使用Passport為Node.js應用程式提供社交認證

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

结论

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

以上是使用Passport為Node.js應用程式提供社交認證的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!