我正在使用 passport-discord 和 passport 来允许用户使用他们的不和谐帐户进行身份验证。
由于某种原因,cookie 没有存储在浏览器中(在前端网站上),我使用 axios(在请求选项中将 withCredentials 设置为 true)向我的快速服务器发出请求,该服务器从请求中获取经过身份验证的用户(req.用户),会话存储在数据库(mongodb atlas)中,但 cookie 没有存储在浏览器中。这在本地有效,但当我在 vercel 等平台上托管网站时无效。cookie 被存储在 API 页面中,而不是在前端网站上,这很奇怪。
api的主文件:
const app = require('express')();
const routes = require('./src/routes'); // all the routes
const passport = require('passport');
const mongoose = require('mongoose');
const session = require('express-session');
const cors = require('cors');
const MongoStore = require('connect-mongo');
require('./src/strategies/discord'); // this is where the users are serialized, deserialized
mongoose.connect('database uri');
app.use(
cors({
origin: [
'api url',
'frontend website url',
],
credentials: true,
})
);
app.use(
session({
secret: 'session secret',
cookie: {
maxAge: 30000,
},
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: 'database uri',
}),
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use('/api', routes);
app.listen(3000, () => {
console.log(`[API] Running on Port 3000`);
});
/strategies/discord.js 文件(用户被序列化和反序列化的地方:
const passport = require('passport');
const DiscordStrategy = require('passport-discord');
const model = require('../models/User');
passport.serializeUser((user, done) => {
console.log(`Serialized: ${user._id}`);
done(null, user._id);
});
passport.deserializeUser(async (id, done) => {
console.log(`Deserialized: ${id}`)
try {
const user = await model.findById(id);
return user ? done(null, user) : done(null, null);
} catch (err) {
console.log(err);
done(err, null);
}
});
passport.use(
new DiscordStrategy(
{
clientID: 'the client id',
clientSecret: 'the app client secret',
callbackURL: `https://apiurl/discord/redirect`,
scope: ['identify', 'guilds'],
},
async (accessToken, refreshToken, profile, done) => {
const { id, username, discriminator, avatar, guilds } = profile;
try {
const found = await model.findByIdAndUpdate(
id,
{
discordTag: `${username}#${discriminator}`,
avatar,
guilds,
},
{
new: true,
}
);
if (found) {
console.log(`User was found`);
return done(null, found);
} else {
const newUser = await new model({
_id: id,
discordTag: `${username}#${discriminator}`,
avatar,
guilds,
}).save();
return done(null, newUser);
}
} catch (err) {
console.log(err);
return done(err, null);
}
}
)
);
auth.js 文件(用户被重定向到 Oauth2 页面):
const router = require('express').Router();
const passport = require('passport');
router.get('/discord', passport.authenticate('discord'));
router.get(
'/discord/redirect',
passport.authenticate('discord'),
(req, res) => {
res.redirect(`http://localhost:3001/guilds`);
}
);
router.get('/', (req, res) => {
if (req.user) {
res.send(req.user);
} else {
return res.status(401).send('Unauthorized'); // I make a request to this url with axios from my frontend website (withCredentials set to true, so the cookies can be sent)
}
});
module.exports = router;
正如您在 auth.js 文件中看到的那样,一旦用户登录,他们就会被重定向到前端网站上的公会页面。我再次向我的 API 发出请求,以获取 discord.js 的共同公会客户端和用户,我检查用户是否登录(req.user 存在),如果是,我发送共同行会或仅发送 401 响应并将用户重定向回主页。
登录网站后,我被重定向到公会页面,然后立即重定向到主页,当我检查控制台时,有一个 401 响应(来自 API)。当我检查我网站的“应用程序”选项卡时,没有 cookie,但 API 页面有 cookie。
我不确定这是否是我的代码或我正在使用的软件包之一的问题,不胜感激。