egg icon indicating copy to clipboard operation
egg copied to clipboard

egg-passport使用passport-oauth2策略不能保存认证状态,一直会重复认证

Open Yunfly opened this issue 8 years ago • 9 comments

加上passport-oauth2后会一直重复认证.. 代码:

//  app/config/plugin.js
exports.passport = {
  enable: true,
  package: 'egg-passport',
};

// app.js
const OAuth2Strategy = require('passport-oauth2').Strategy;

module.exports = app => {

  app.passport.use('oauth2',new OAuth2Strategy({
      authorizationURL: app.config.passportYun9.authorizationURL,
      tokenURL: app.config.passportYun9.tokenURL,
      clientID: app.config.passportYun9.clientID,
      clientSecret: app.config.passportYun9.clientSecret,
      callbackURL: app.config.passportYun9.callbackURL,
      passReqToCallback:true
    },
    function(req,accessToken, refreshToken, profile, done) {
      const user = {
        accessToken:accessToken,
        refreshToken:refreshToken
      };
      console.log('doVerify');
      app.passport.doVerify(req, user, done);
    }
  ));
};
// app/router.js
app.get('/',app.passport.authenticate('oauth2'), 'home.index');
  app.get('/auth/callback',app.passport.authenticate('oauth2',{
    successRedirect: '/home',
    failureRedirect: '/login'
  }),  'home.index');
  app.get('/home', app.passport.authenticate('oauth2'),  'home.index');

像这样在‘/home’中添加认证中间件就会一直重复认证,想知道是思路不对还是需要重写一个oauth2的认证插件?

Yunfly avatar Sep 04 '17 07:09 Yunfly

参考其他几个插件试试?

atian25 avatar Sep 04 '17 08:09 atian25

@atian25 试过了还是会一直重复认证,successRedirect的路由没有添加认证中间件

Yunfly avatar Sep 05 '17 02:09 Yunfly

@fengmk2 https://github.com/Yunfly/egg-passport-oauth2 我把我的代码放上去了,能帮我分析下吗

Yunfly avatar Sep 05 '17 02:09 Yunfly

目前还没充足的时间来排查,先关注。

fengmk2 avatar Sep 05 '17 02:09 fengmk2

@fengmk2 嗯嗯,照着教程上跑的,就是不知道怎么没实现

Yunfly avatar Sep 05 '17 03:09 Yunfly

在成功回调页面验证this.isAuthenticated()时,关闭浏览器重新访问也是true,但是也没有设置session:false,初步断定是关闭浏览器时,session.passport没有被清除。

Yunfly avatar Sep 13 '17 07:09 Yunfly

// app/router.js
app.get('/',app.passport.authenticate('oauth2'), 'home.index');
app.get('/auth/callback',app.passport.authenticate('oauth2',{
  successRedirect: '/home',
  failureRedirect: '/login'
}),  'home.index');
app.get('/home', app.passport.authenticate('oauth2'),  'home.index');

你这样配置,是会产生这样的效果:

  1. 路由到 '/' 时跳转到授权验证页面
  2. 授权成功后重定向到 '/home',失败则重定向到 '/login',
  3. 路由到 '/home',会跳转到授权验证页面 所以会造成一直重复认证,死循环

解决方法: 路由到 '/home' 时,应该把授权验证去掉

app.get('/home', 'home.index');

OnedayLiu avatar Dec 10 '17 15:12 OnedayLiu

@Yunfly 在授权验证成功之前,ctx. isAuthenticated() 的值是 false,验证成功后才是 truesession 是存在 cookie 里面,是有有效期的,所以关闭浏览器也不行,如果你想清除登录状态,是否可以做个退出按钮让用户点击退出呢?

OnedayLiu avatar Dec 10 '17 15:12 OnedayLiu

@Yunfly 关于 eggsession 详细介绍,请看 https://eggjs.org/zh-cn/core/cookie-and-session.html

OnedayLiu avatar Dec 10 '17 15:12 OnedayLiu