Node.js 如何正确使用passport.js
我正在尝试passport库验证api请求。首先,我使用express框架创建了一个NodeJS应用程序。该项目包含一些服务于某些数据的API。在公用文件夹中,它包含index.html页面,其中包含用户名和密码字段 Index.htmlNode.js 如何正确使用passport.js,node.js,passport.js,Node.js,Passport.js,我正在尝试passport库验证api请求。首先,我使用express框架创建了一个NodeJS应用程序。该项目包含一些服务于某些数据的API。在公用文件夹中,它包含index.html页面,其中包含用户名和密码字段 Index.html <form action="/login" method="post"> <div> <label>Username:</label> <input type="te
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="name"/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Log In"/>
</div>
</form>
现在,当我点击localhost:7000时,它会打开登录页面,当我从userList
单击submit with username时,它会返回完成的登录。这很好
现在,每个调用都通过反序列化user
方法进行
问题是,当我直接调用其他URL而不点击/登录(验证用户)时,它们也可以正常工作并返回数据
我原以为如果请求未通过身份验证,那么所有其他调用都将失败,因为反序列化用户
正在拦截每个请求,但在这种情况下,不会调用passport方法
这就是它的工作原理吗?或者我遗漏了什么?您需要添加一个中间件,以检查您的用户是否经过身份验证:
isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
//if user is logged in, req.isAuthenticated() will return true
return next();
}
res.redirect('/login');
};
您必须像这样使用中间件:
//if user not authenticated, he will be redirect on /login
app.get('/done', isAuthenticated, (req, res) => {
res.send("done")
});
我缺少用于验证所有后续请求的中间件。所以我创建了
isAuthenticated
方法(谢谢@Sombrero)
然后在每一个请求中
app.get('/done', isAuthenticated, (req, res) => {
res.send("done")
});
但在每个请求中都很难使用isAuthenticated
方法。所以我创建了一个API列表数组,它是公共的,并添加了中间件来拦截每个请求,并更新了isAuthenticated
方法来忽略公共API
// list of apis for which authentication is not required
private static publicApiList: string[] = ["/login"];
// request interceptor that will check user authentication
private static isAuthenticated = (req, res, next) => {
console.log("Authenticating :", req.originalUrl)
if (req.isAuthenticated() || Server.publicApiList.indexOf(req.originalUrl) > -1) {
return next();
}
res.redirect('/login');
};
然后将此方法用作中间件
app.use(Server.isAuthenticated)
你不认为这应该是自动的吗?我的意思是,我不应该为所有请求设置任何中间件。不,这不是自动的,比如,你可以选择哪些路由是公共的,哪些路由是用户需要登录才能访问的。我知道这已经很长时间了,但是这个策略可能面临的一个问题是,如果您正在设计一个Restful API并决定执行以下操作:GET/posts(返回posts的公共端点)和POST/posts(创建posts的私有端点)。如果使用上述功能,您将无法区分路线。
// list of apis for which authentication is not required
private static publicApiList: string[] = ["/login"];
// request interceptor that will check user authentication
private static isAuthenticated = (req, res, next) => {
console.log("Authenticating :", req.originalUrl)
if (req.isAuthenticated() || Server.publicApiList.indexOf(req.originalUrl) > -1) {
return next();
}
res.redirect('/login');
};
app.use(Server.isAuthenticated)