[英]Google+ Sign-In - Page accessible for logged in users only
我决定在页面上使用社交媒体权益,目前正在实施Google+登录。
我的网站上的页面之一应仅可用于登录用户访问(向页面添加内容)。 我正在通过JavaScript将用户登录到网站。
我知道javascript是在客户端执行的,但我很好奇是否有可能仅使用javascript限制对特定页面的访问。
这是执行此操作的一种方法,并且在整个注释中都包含以下内容:
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();
});
}
}
}
);
};
One idea is to wrap the above code in some more middleware, to make it easier to read:
// 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);
您不能仅使用客户端javascript执行可靠的访问控制。
这是因为由于javascript是在用户的浏览器上执行的,所以用户将能够绕过您在此处设置的所有访问控制规则。
您必须在服务器端执行访问控制,以Python代码为例。
通常,人们还在客户端执行某种访问控制检查,不是为了阻止访问,而是例如隐藏/禁用用户无法使用的按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.