使用express+passport实现的Nodejs完整新浪微博 oauth例子
使用express+passport实现的Nodejs完整新浪微博 oauth例子
使用express+passport实现的一个完整新浪微博oauth例子,可以在hackthon时实现快速实现新浪微博登录功能(也可快速添加其他oauth provider)
主要功能:
- 本地email+password登录
- 直接新浪weibo登录
- 本地登录后绑定新浪微博账号
- 解除绑定功能
依赖:
- Express 4.0
- Passportjs + passport-weibo
- Mongodb(Mongoose)
地址: node-auth-weibo
3 回复
非常感谢!
以下是使用 express
和 passport
实现的 Node.js 完整新浪微博 OAuth 示例。这个例子展示了如何实现本地登录、新浪微博登录、本地账户与新浪微博账户绑定及解绑等功能。
1. 初始化项目
首先安装必要的依赖:
npm init -y
npm install express passport passport-weibo connect-flash mongoose body-parser express-session
2. 配置文件
创建一个 .env
文件来存储环境变量:
WEIBO_CLIENT_ID=your_weibo_client_id
WEIBO_CLIENT_SECRET=your_weibo_client_secret
MONGO_URI=mongodb://localhost:27017/auth-example
使用 dotenv
来加载这些变量:
require('dotenv').config();
3. Express 和 Passport 配置
创建一个 app.js
文件,并配置 express
和 passport
:
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const WeiboStrategy = require('passport-weibo-oauth2').Strategy;
const flash = require('connect-flash');
const mongoose = require('mongoose');
const app = express();
// MongoDB connection
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
// Session configuration
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false
}));
// Passport initialization
app.use(passport.initialize());
app.use(passport.session());
// Flash messages
app.use(flash());
// Body parser
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Passport strategy for Weibo
passport.use(new WeiboStrategy({
clientID: process.env.WEIBO_CLIENT_ID,
clientSecret: process.env.WEIBO_CLIENT_SECRET,
callbackURL: "/auth/weibo/callback"
}, (accessToken, refreshToken, profile, done) => {
// Here you would typically save the profile and accessToken to your database
return done(null, profile);
}));
// Serialize and deserialize user
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
// Routes
app.get('/auth/weibo', passport.authenticate('weibo'));
app.get('/auth/weibo/callback',
passport.authenticate('weibo', { failureRedirect: '/login' }),
(req, res) => {
res.redirect('/');
}
);
app.listen(3000, () => console.log('Server started on port 3000'));
4. 模型定义
定义用户模型:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
email: String,
password: String,
weiboId: String,
weiboUsername: String
});
module.exports = mongoose.model('User', UserSchema);
5. 绑定和解绑功能
你可以通过增加 API 端点来处理绑定和解绑逻辑。例如:
app.post('/bind-weibo', (req, res) => {
const userId = req.user._id;
const weiboId = req.body.weiboId;
const weiboUsername = req.body.weiboUsername;
User.findByIdAndUpdate(userId, {
weiboId,
weiboUsername
}, (err, user) => {
if (err) return res.status(500).send(err);
res.send(user);
});
});
app.post('/unbind-weibo', (req, res) => {
const userId = req.user._id;
User.findByIdAndUpdate(userId, {
weiboId: null,
weiboUsername: null
}, (err, user) => {
if (err) return res.status(500).send(err);
res.send(user);
});
});
6. 安全性注意事项
确保你的应用在生产环境中使用 HTTPS,保护好你的密钥和敏感数据。此外,确保正确地处理错误和异常情况。
完整的代码可以在这个仓库中找到:node-auth-weibo
这个例子提供了一个基础框架,你可以根据需要进行扩展和修改。