【发布时间】:2017-08-06 21:30:02
【问题描述】:
我的问题与one 类似,那里的所有答案都没有帮助我。
我正在使用带有本地策略的 Passport.js (passport-local-mongoose)。 下面的中间件适用于 Postman,但每当我从我的 React 客户端尝试时都会失败。
exports.isLoggedIn = (req, res, next) => {
console.log(req.user) // undefined with react, but works from postman
if (req.isAuthenticated()) {
return next();
}
}
这是我的 app.js:
require('./handlers/passport');
app.use(cors())
app.use(session({
secret: process.env.SECRET,
key: process.env.KEY,
resave: true,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());
handlers/passport.js:
const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('User');
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
user.js(模型):
...
userSchema.plugin(passportLocalMongoose, { usernameField: 'email' });
客户代码:
const url = 'http://localhost:7777/users/<id>';
const config = {
headers: {
'Content-Type': 'application/json',
},
};
axios.put(url, data, config)
.then(res => console.log(res))
.catch(err => console.log(err));
我错过了什么吗? passportLocal 策略是否意味着我不能像我的示例那样使用 API 和客户端?谢谢:D
【问题讨论】:
-
在 React 应用程序中显示您向服务器发送请求的代码。
-
与普通的 http 调用没有什么不同。我正在使用 axios.js 而不发送任何标头,我已经尝试使用 const headers = { credentials: 'include' };
-
当您在客户端中对用户进行身份验证时,我不完全确定您是如何处理令牌的。因此,由于您使用的是 axios,因此您需要明确设置您的请求授权,您可以将其包含在后续请求中。检查this
-
嘿@Rowland,那么我到底需要在我的授权标头中设置什么?这是我第一次使用passport.js,我不知道我应该将什么存储为“令牌”。在我成功/登录后,我可以看到“set-cookie:”属性作为响应头,我可以通过document.cookie访问它,在后续请求中将其发送到服务器也不起作用。
标签: javascript node.js express authentication passport.js