我计划建立谷歌登录使用Node JS
,Express JS
和Passport JS
。在此过程中,我使用应用程序凭据配置了Google策略,创建了一个带有登录按钮的示例.ejs
页面,并能够登录并检索用户配置文件。后来,我删除了示例页,并尝试将所有静态角4文件(使用角-cli构建)放置在Public
目录中,并编写了以下逻辑:
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
if (req.isAuthenticated()) {
res.redirect("/home");; // Angular route
} else {
// require the user to log in
// redirects to Google Sign-in page
res.redirect("/auth/google");
}
});
现在,当我启动服务器并访问http://localhost:3000
时,我没有看到任何重定向到Google登录页面,而是浏览器直接呈现http://localhost:3000/home
。
因此,为了对用户进行身份验证,然后将用户重定向到主页,我应该做哪些更改。以及保护应用程序中的其他路由/子路由?
发布于 2017-08-18 16:55:03
检查if
请求有一个会话的简单方式..。
app.get('/home', function(req, res) {
if(req.session){ //session exists (requesting user has a session)
// Angular route code goes here to prevent non-authed user access
}else{res.redirect("/");} //or res.redirect("/auth/google");
});
...or使用像连接-确保-登录这样的模块
确保身份验证
app.get('/home',
ensureLoggedIn('/auth/google'),
function(req, res) {
// Angular route code goes here to prevent non-authed user access
});
如果用户没有创作,请求将被重定向到/auth/google
,原始请求URL (/home
)将保存到req.session.returnTo的会话中。
https://stackoverflow.com/questions/45766651
复制