当前位置: 首页 > 知识库问答 >
问题:

passport-github如何提取会话cookie以知道用户已经登录

凌波峻
2023-03-14

我正在为我的应用程序构建一个passport-github身份验证。但是我想目前我还不知道如何从请求中提取cookie来说明用户已经登录了。所以每次当我进入主页时,我会被重定向到/login。

我的代码大致如下所示:

passport.use(new GitHubStrategy({
    clientID: authConfig.GITHUB_CLIENT_ID,
    clientSecret: authConfig.GITHUB_CLIENT_SECRET,
    callbackURL: "http://127.0.0.1:8080/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    return db.user.findOne({where:{github_id:profile.id}})
    .then(data=>{
      if (data) {
        return done(null,data);
      } else {
        return db.user.build({ github_id: profile.id }).save()
        .then(()=>{
          return db.user.findOne({where:{github_id:profile.id}})
        })
        .then(data=>{
          return done(null,data);
        })
      }
    });
  }
));

// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing
passport.serializeUser(function(user, done) {
  console.log("serialize>>>>>", user.github_id);
  done(null, user.github_id);
});

passport.deserializeUser(function(id, done) {
  console.log("deserialize>>>>", id);
  db.user.findOne({where:{github_id: id}})
  .then(user=>{
    done(null, user.toJSON());
  })
});

我确定了会议:

app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

并且我有一个isAuthenticated函数来检查请求信息:

function isAuthenticated (req, res, next) {
  // If the user is logged in, continue with the request to the restricted route
  console.log("req.user is>>>>", req);
  if (req.isAuthenticated()) {
    return next();
  }
  // If the user isnt' logged in, redirect them to the login page
  return res.redirect("/index");
}

我正在使用这个passport-github lib。我无法从req中获得一些有用的信息

更新为包含路由:以下是路由:

    const isAuthenticated = require('./middleware/isAuthenticated.js');
router
    .get('/index', query.renderIndex)
    .get('/', isAuthenticated, query.displayRepos)
    .post('/', query.queryRepoTopic)
    .post('/trending', query.addRepo)
    .post('/addTopic', query.addTopic)
    .get('trending', query.updateScore);

router.get('/login', auth.loginPage)
  .get('/auth/github',
    passport.authenticate('github', { scope: [ 'user:email' ] }),
    function(req, res){}
  )
  .get('/auth/github/callback', 
    passport.authenticate('github', { failureRedirect: '/login' }),
    auth.signInRedirect
  )
  .get('/logout', auth.logout);

下面是执行逻辑的控制器函数:

const loginPage = (req, res) => {
  res.render('index');
}

// signin a user in 
const signInRedirect = (req, res) => {
  console.log("here in callback>>>");
  console.log("req.user is>>>>", req.user);
  //res.json("you have successfully logged in!");
  res.redirect('/');
}

const logout = (req, res) => {
  req.logout();
  res.redirect('/index');
}

共有1个答案

柯鸿云
2023-03-14

我看到您有这样的路由配置:

    const isAuthenticated = require('./middleware/isAuthenticated.js');
    router
        .get('/index', query.renderIndex)
        .get('/', isAuthenticated, query.displayRepos)
...

如果您希望调用localhost:3000,并在未登录时重定向到auth/github,则可以如下所示更改isauthenticatedfunction:

function isAuthenticated (req, res, next) {
  // If the user is logged in, continue with the request to the restricted route
  console.log("req.user is>>>>", req);
  if (req.isAuthenticated()) {
    return next();
  }
  // If the user isnt' logged in, redirect them to the github login page.
  return res.redirect("/auth/github");
}

这意味着,当您尝试调用'/'时,isauthenticated将检查是否设置了req.user(if(req.isauthenticated())),如果没有,则重定向到/auth/github路由

你试过这个吗?

有了它就能帮上忙了!

 类似资料:
  • 问题内容: 我想在学习活动中构建一个简单的Web应用程序。如果遇到首次访问者,Webapp应该要求用户输入他们的email_id,否则它会通过cookie记住用户并自动登录以执行功能。 这是我第一次创建基于用户的Web应用程序。我心中有一个蓝图,但是我无法弄清楚如何实现它。首先,我对收集用户cookie的方式感到困惑。我研究了各种教程和flask_login,但是与flask_login所实现的相

  • 我有一个与CRUD能力的平均应用程序完全测试与邮递员。我一直试图坚持登录相当长的一段时间,现在没有运气。我已经阅读并尝试了以下内容 护照文档 Toon Io关于登录的博客 快速会话 苏格兰io,节点auth容易 加上一些其他简单的阅读材料(很多这样的问题) 但是我只能注册和登录一个用户,不能用会话持久登录。 下面是我对用户登录的理解,包括我的项目中的代码示例和邮递员结果的截图以及控制台日志。 我有

  • 问题内容: 我已经阅读了两天的信息和样本,但不确定此后是否完成了所有身份验证过程。 我怎么知道我是否已登录,例如,我将有一个带有登录或注销按钮的导航栏,下面是否有一些变量,如代码? 问题答案: 如果用户已登录,则将为中的每个请求创建一个对象,您可以检查任何中间件是否存在: 您可以为此创建简单的中间件,该中间件将检查用户是否已登录,如果没有,则将重定向到页面: 并使用它:

  • 我正在使用Firebase云功能与Express和Firebase托管来为我的多页面站点服务。我已经成功地实现了服务器端cookie,如下文所述: 我正在使用Firebase Web SDK(JavaScript)访问Firebase Cloud Firestore。为此,我需要在客户端为当前登录的用户获取idToken,如下所示: 这对我来说似乎是多余的,因为我已经知道哪个用户是通过我的服务器c

  • 问题内容: 我不确定是否已经使用cmd:docker login在cmd行中登录了Docker注册表。如何在不尝试推送的情况下测试或查看是否已登录? 问题答案: 编辑2020 再次提到( 已关闭的 )github问题,指出那里没有实际的会话或状态。 docker login实际上并没有创建任何持久性会话,它只是将用户的凭据存储在磁盘上,以便在需要身份验证时可以读取它们以登录 正如其他人指出的那样,

  • 问题内容: 我正在尝试确定基于ajax的登录表单进行身份验证和设置客户端cookie的最安全方法。 和 http://www.codinghorror.com/blog/archives/001167.html 所以,我想我的核心问题是… 1)使用纯Ajax设置cookie是否安全,如果是,最安全的方法是什么(httpOnly + SSL +加密值等)? 2)纯ajax方法是否涉及设置cookie