さて、私が見てきたことから、passport.js の使用は機能し、うまく機能します。ただし、特定のユーザーを適切に除外する方法がわかりません。ユーザーにログイン方法を提供するだけでなく、アプリケーションがアクセスを制限することを意図している場合、passport.js を使用してログインを制限するにはどうすればよいですか? 現状では、ユーザーは/login
自分の Google アカウントにアクセスしてログインするだけで、内部にアクセスできます。
3741 次
2 に答える
9
これを行う 1 つの方法を次に示します。全体にコメントが付いています。主なことは、著者からのこのページを理解することです: http://passportjs.org/guide/authenticate/、この例でもう少し説明します...
下から上に読む方が簡単かもしれません:
var authenticate = function(req, success, failure) {
// Use the Google strategy with passport.js, but with a custom callback.
// passport.authenticate returns Connect middleware that we will use below.
//
// For reference: http://passportjs.org/guide/authenticate/
return passport.authenticate('google',
// This is the 'custom callback' part
function (err, user, info) {
if (err) {
failure(err);
}
else if (!user) {
failure("Invalid login data");
}
else {
// Here, you can do what you want to control
// access. For example, you asked to deny users
// with a specific email address:
if (user.emails[0].value === "no@emails.com") {
failure("User not allowed");
}
else {
// req.login is added by the passport.initialize()
// middleware to manage login state. We need
// to call it directly, as we're overriding
// the default passport behavior.
req.login(user, function(err) {
if (err) {
failure(err);
}
success();
});
}
}
}
);
};
1 つのアイデアは、読みやすくするために、上記のコードをいくつかのミドルウェアでラップすることです。
// This defines what we send back to clients that want to authenticate
// with the system.
var authMiddleware = function(req, res, next) {
var success = function() {
res.send(200, "Login successul");
};
var failure = function(error) {
console.log(error);
res.send(401, "Unauthorized");
};
var middleware = authenticate(req, success, failure);
middleware(req, res, next);
};
// GET /auth/google/return
// Use custom middleware to handle the return from Google.
// The first /auth/google call can remain the same.
app.get('/auth/google/return', authMiddleware);
(これはすべて、Express を使用していることを前提としています。)
于 2012-12-06T00:02:33.277 に答える
0
これを試して。
googleLogin: function(req, res) {
passport.authenticate('google', { failureRedirect: '/login', scope: ['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'] }, function(err, user) {
req.logIn(user, function(err) {
if (err) {
console.log(err);
res.view('500');
return;
}
var usrEmail = user['email'];
if(usrEmail.indexOf("@something.com") !== -1)
{
console.log('successful');
res.redirect('/');
return;
}
else
{
console.log('Invalid access');
req.logout();
res.view('403');
return;
}
});
})(req, res);
}
*
于 2014-12-16T10:37:18.243 に答える