我有一个运行在localhost:3000上的快速应用程序,在这里我使用护照js处理身份验证,还有一个运行在localhost:8080上的react应用程序。当用户进行身份验证时,我将信息存储在mobx存储中(类似于redux),但是当页面刷新时,信息全部消失了。
我想在服务器上有一个URL,可以向其请求当前活动的用户(即localhost:3000 / auth / getActiveUser),它应该给我当前登录的用户。
当我从浏览器转到localhost:3000 / auth / getActiveUser时,它工作正常。但是问题是当我从客户端获取内容时,没有将快速cookie即connect.sid作为标头传递,即
fetch(THE_URL_ABOVE)
。我试图手动将Cookie作为标头传递,但是服务器不想验证我的请求。
有什么想法可以做到吗?
import express from 'express';
import passport from 'passport';
import session from 'express-session';
import router from './routes/routes';
import authRouter from './routes/authRoutes';
import middleware from './middleware';
import keys from './keys';
const MongoDBStore = require('connect-mongodb-session')(session);
const app = express();
const store = new MongoDBStore({
uri: 'mongodb://localhost:27017/bloggingApp',
collection: 'userSessions',
});
store.on('error', (err) => {
console.log(err);
});
middleware(app);
app.use(session({
secret: keys.session.cookieKey,
resave: false,
saveUninitialized: false,
store,
cookie: { httpOnly: false }, // false so I can access it as document.cookie on front end
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done) => {
// done(err, usr prop to make a cookie)
done(null, user.id);
});
// get a user from the id
passport.deserializeUser(async (id, done) => {
const usr = await User.findById(id);
// attach usr to req later
done(null, usr);
});
passport.use(new GoogleStrategy({
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret,
callbackURL: '/auth/google/redirect',
}, async (accessToken, refreshToken, profile, people, done) => {
console.log(people);
// callback for auth
// if user not found, then save
let usr = await User.findOne({ googleID: people.id });
// save user in users collection
if (!usr) {
const user = new User({
name: people.displayName,
email: people.emails[0].value,
googleID: people.id,
image: people._json.image.url,
});
usr = await user.save();
console.log('new user created');
} else {
console.log('The user is ', usr);
}
// calls serializeUser
done(null, usr);
}));
const authRouter = Router();
authRouter.get('/google', passport.authenticate('google', {
scope: ['profile', 'email'],
}));
authRouter.get('/logout', (req, res) => {
req.logout();
// res.send('logout using passport');
res.set('Content-Type', 'text/html');
res.end(popupTools.popupResponse({
status: true,
message: 'Logged out!',
}));
});
// callback after loging in
authRouter.get('/google/redirect',
passport.authenticate('google'),
(req, res) => {
// here we have the user as req.user
res.set('Content-Type', 'text/html');
res.end(popupTools.popupResponse({
status: true,
message: {
data: req.user,
},
}));
}
);
// this needs to be fixed
authRouter.get('/getActiveUser', (req, res) => {
console.log(req.isAuthenticated());
res.json({
user: req.user,
});
});