本教程使用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中文网其他相关文章!