5

我想重现 plunker 如何管理匿名帐户。

Plunker 可以识别匿名用户。例如,我们可以将 plunker 保存为anonym然后freeze它。因此,

  1. 只有同一个用户(在清除浏览器历史记录之前)拥有对此插件的完全访问权限(例如,保存修改、解冻)。

  2. 如果同一用户在另一个浏览器中打开它或其他用户打开相同的链接,他们不能save进行任何修改;他们必须这样fork做。

在我的网站中,我使用管理命名用户的local策略。passport.js例如,

router.post('/login', function (req, res, next) {
    if (!req.body.username || !req.body.password)
        return res.status(400).json({ message: 'Please fill out all fields' });

    passport.authenticate('local', function (err, user, info) {
        if (err) return next(err);
        if (user) res.json({ token: user.generateJWT() });
        else return res.status(401).json(info);
    })(req, res, next);
});

我使用 alocalStorage来存储令牌。例如,

auth.logIn = function (user) {
    return $http.post('/login', user).success(function (token) {
        $window.localStorage['account-token'] = token;
    })
};

auth.logOut = function () {
    $window.localStorage.removeItem('account-token');
};

有谁知道是否passport.js有任何策略或现有工具可以像 plunker 那样管理匿名帐户?否则,有没有一种传统的方法可以实现这一目标?

4

2 回答 2

3

Passport 允许匿名身份验证。有一个相同的护照匿名策略:

app.get('/',
  // Authenticate using HTTP Basic credentials, with session support disabled,
  // and allow anonymous requests.
  passport.authenticate(['basic', 'anonymous'], { session: false }),
  function(req, res){
    if (req.user) {
      res.json({ username: req.user.username, email: req.user.email });
    } else {
      res.json({ anonymous: true });
    }
  });

这使用了您的基本策略,如果您使用本地身份验证,您可以将其替换为本地策略。如果没有提供任何内容,它会退回到匿名策略,如下所示:

passport.use(new BasicStrategy({
  },
  function(username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // Find the user by username.  If there is no user with the given
      // username, or the password is not correct, set the user to `false` to
      // indicate failure.  Otherwise, return the authenticated `user`.
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false); }
        if (user.password != password) { return done(null, false); }
        return done(null, user);
      })
    });
  }
));

// Use the BasicStrategy within Passport.
//   This is used as a fallback in requests that prefer authentication, but
//   support unauthenticated clients.
passport.use(new AnonymousStrategy());

完整的例子可以在这里找到:- https://github.com/jaredhanson/passport-anonymous/blob/master/examples/basic/app.js

于 2017-04-27T16:39:50.523 回答
0

请记住,过期日期较长的 cookie 是识别匿名用户的方式。这与任何试图通过用户名和密码验证用户的服务器端技术相同,然后只为 http 请求设置一个 cookie。

于 2017-04-27T19:39:29.383 回答