本教程使用Passport.js(一種流行的身份驗證中間件)在Node.js Web應用程序中演示了Facebook和GitHub身份驗證。 護照簡化了OAuth和OpenID Connect Integration。
密鑰概念:
passport-facebook
passport-github
>
mkdir AuthApp cd AuthApp npm init -y
auth.html
<!DOCTYPE html> <html> <head> <title>Node.js OAuth</title> </head> <body> <a href="https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76">Sign in with Facebook</a><br><br> <a href="https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac">Sign in with GitHub</a> </body> </html>
express App:
npm install express passport --save
運行應用程序()並驗證index.js
顯示HTML。停止應用程序(
const express = require('express'); const app = express(); const port = process.env.PORT || 3000; app.get('/', (req, res) => res.sendFile('auth.html', { root: __dirname })); app.listen(port, () => console.log(`App listening on port ${port}`));
node index.js
http://localhost:3000
Ctrl C
護照配置:
>安裝提供商策略:安裝Facebook和github策略:
>
中的護照設置npm install passport-facebook passport-github --save
> Facebook身份驗證:index.js
const passport = require('passport'); app.use(passport.initialize()); app.use(passport.session()); app.get('/success', (req, res) => res.send("Successfully logged in!")); app.get('/error', (req, res) => res.send("Error logging in.")); passport.serializeUser((user, done) => done(null, user)); passport.deserializeUser((user, done) => done(null, user));
遵循Facebook的說明,以創建一個新應用並獲得您的>和。
>在>中配置Facebook策略:App ID
App Secret
記住要將Facebook應用程序的有效OAuth重定向URIS配置為
github身份驗證:index.js
const FacebookStrategy = require('passport-facebook').Strategy; const FACEBOOK_APP_ID = 'YOUR_FACEBOOK_APP_ID'; // Replace with your App ID const FACEBOOK_APP_SECRET = 'YOUR_FACEBOOK_APP_SECRET'; // Replace with your App Secret passport.use(new FacebookStrategy({ clientID: FACEBOOK_APP_ID, clientSecret: FACEBOOK_APP_SECRET, callbackURL: "https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76/callback", profileFields: ['id', 'displayName', 'photos', 'email'] //Optional: Specify fields to retrieve }, (accessToken, refreshToken, profile, done) => { done(null, profile); })); app.get('https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76', passport.authenticate('facebook')); app.get('https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76/callback', passport.authenticate('facebook', { failureRedirect: '/error' }), (req, res) => res.redirect('/success') );
http://localhost:3000https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76/callback
>創建一個github應用程序:
>中的github策略:
>
將您的github應用程序的授權回調URL配置為Client ID
>Client Secret
>
運行應用程序: 啟動服務器(node index.js
)並測試Facebook和GitHub登錄鏈接。 該路線將表示成功的身份驗證。 請記住,用您的實際值替換佔位符和秘密。 這提供了一個基本框架; 對於生產就緒的應用程序,需要在數據庫中進行錯誤處理和用戶持久性。
以上是Node.js應用程序的護照身份驗證的詳細內容。更多資訊請關注PHP中文網其他相關文章!