护照oauth2用于交换访问令牌

时间:2020-03-06 20:03:39

标签: node.js express passport.js laravel-passport passport-local

是否可以只使用passport-oauth2来进行身份验证代码的accessToken交换。因为前端完成了将用户重定向到oauth登录页面和uri重定向的工作,所以直接命中了Express服务器端点并调用了以下代码。

passport.js:

        passport.use(new OAuth2Strategy({
        authorizationURL: 'https://www.example.com/oauth2/authorize',
        tokenURL: 'https://www.example.com/oauth2/token',
        clientID: EXAMPLE_CLIENT_ID,
        clientSecret: EXAMPLE_CLIENT_SECRET,
        callbackURL: "http://localhost:3000/auth/example/callback"
      },
      function(accessToken, refreshToken, profile, cb) {
        User.findOrCreate({ exampleId: profile.id }, function (err, user) {
          return cb(err, user);
        });
      }
    ));

上面的回调代码获取用户数据。所以我只在下面的代码中使用回调。

 app.js:


     function adminIsLoggedIn(req, res, next) {

     // if user is authenticated in the session, carry on
      if (req.isAuthenticated())
         return next();

     // if they aren't redirect them to the home page
      res.redirect('/');
   }

  // required for passport session
  app.use(session({
    secret: 'secrettexthere',
    saveUninitialized: true,
    resave: true
  }));

  // Init passport authentication
  app.use(passport.initialize());
  // persistent login sessions
  app.use(passport.session());


   initializePassportoAuth2Config(app);

   app.use('/admin', adminIsLoggedIn, admin);

  //app.get('/auth/example',
    //passport.authenticate('oauth2'));

  app.get('/auth/example/callback',
    passport.authenticate('oauth2', { failureRedirect: '/login' }),
    function (req, res) {
      // Successful authentication, redirect home.
      res.redirect('/');
    });

但是我得到一些不一致的结果,即当从其他控制器调用req.isAuthenticated()时,它返回false。当我进入req.isAuthenticated()方法的代码时,我发现其中没有用户对象。

在整个过程中,我从未看到过password.deserliazeUser()。

更新:邮递员呼叫有效,但浏览器呼叫无效

0 个答案:

没有答案