【问题标题】:How to secure Angular 4 routes using Passport JS?如何使用 Passport JS 保护 Angular 4 路由?
【发布时间】:2018-01-27 17:32:08
【问题描述】:

我计划使用Node JSExpress JSPassport JS 设置Google 登录。在此过程中,我使用应用程序凭据配置了 Google 策略,创建了一个带有登录按钮的示例 .ejs 页面,并且我能够登录并检索用户配置文件。后来我把示例页面去掉了,尝试把所有的静态Angular 4文件(使用angular-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

那么,我应该进行哪些更改才能对用户进行身份验证,然后将用户重定向到主页。并且还保护应用程序中的其他路由/子路由?

【问题讨论】:

    标签: node.js angular google-app-engine express passport.js


    【解决方案1】:

    检查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");
    });
    

    ...或者使用像connect-ensure-login这样的模块

    确保身份验证

    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。

    【讨论】:

      猜你喜欢
      • 2016-09-13
      • 1970-01-01
      • 2017-02-11
      • 2020-05-18
      • 1970-01-01
      • 2020-02-13
      • 2021-10-19
      • 2017-10-14
      • 2018-08-20
      相关资源
      最近更新 更多