【问题标题】:how to prevent user from accessing webpage directly in node.js?如何防止用户直接在 node.js 中访问网页?
【发布时间】:2016-01-20 20:19:41
【问题描述】:

您好,我在阻止用户通过输入 URL 访问我的网站时遇到问题。我有一个登录名,我希望它是访问我的/factory/homepage.html 页面的唯一途径。 但是如果用户在 URL 字段中输入/factory/homepage.html,他们就可以访问 homepage.html。 我已经在使用app.get('/factory/'),但我的res.redirect('/website/userLogin.html') 没有重定向到登录页面。 这是我的代码:

app.get('/factory/*', function(req,res,next){
   console.log("going through app.get...");
   res.redirect('../website/userLogin.html');
   console.log('after redirect...');
});

输出是:

going through app.get...
after redirect...

然后用户被带到factory/homepage.html。我也试过app.use('/factory/*'),但没有运气。仅当输入了我的工厂目录中不存在的路径时,重定向才有效,例如 /factory/hello.html 将重定向到 /website/userLogin.html

我希望目录/factory 无法通过输入网址进行访问。然后我会实现一个中间件函数来检查用户是否被认证。

任何帮助将不胜感激!

【问题讨论】:

  • 希望我没有误解你.. 但我认为解决方案是简单的身份验证问题。您可以设置一个 app.get(index) 并检查请求是否经过身份验证,如果没有,则重定向到其他页面?
  • 如果您正在检查他们是否登录,为什么他们先访问登录页面再访问另一个页面有什么关系?为什么认证不够?
  • 可能相关:CSRF
  • @fzxt 我遇到的问题是重定向,重定向仅在我的目录中不存在路径时才有效。如果输入了正确的路径名,则重定向不起作用,用户会被直接带到页面。
  • @Quentin 如果我发现用户未通过身份验证,如果他们输入正确的路径,我重定向到任何其他页面都不起作用。

标签: javascript node.js express response.redirect


【解决方案1】:

我会尝试这样的事情。

app.get('/factory/*', function(req,res,next){

   var authenticated = false;

   //do something to authenticate user

   if(authenticated === true){
       //user is already authenticated
       res.redirect('/factory/homepage.html');
   }else{
       //redirect to login
       res.redirect('../website/userLogin.html');
   }
});

【讨论】:

  • 我尝试了您的建议,但我仍然被直接带到 /factory/homepage.html 页面。 else 代码被执行,因为 authenticated 等于 false 但 res.redirect 不执行。
  • 如果用户已通过身份验证,请将//do something to authenticate user 替换为将authenticated 更改为true 的函数。
猜你喜欢
  • 2021-08-29
  • 1970-01-01
  • 2021-10-08
  • 2012-05-22
  • 2010-11-05
  • 2010-09-16
  • 1970-01-01
  • 2018-04-24
  • 2023-03-09
相关资源
最近更新 更多