简体   繁体   English

nodeJS,angularJS应用程序中的页面请求上的服务器身份验证

[英]Server authentication on page request in nodeJS, angularJS Application

I am using passport.js for authentication. 我正在使用passport.js进行身份验证。 My requirement is that, anyone should not be able to access a particular page (say, '/restricted'), if one is not logged in. 我的要求是,如果未登录某个页面,则任何人都不能访问该页面(例如,“ / restricted”)。

Right now, in my application, anyone can access "localhost:3000/#/restricted" url directly. 现在,在我的应用程序中,任何人都可以直接访问“ localhost:3000 /#/ restricted” URL。

I am able to stop this and allow only logged in users to access the page by using Rorschach120 's solution in Redirect on all routes to login if not authenticated . 我可以停止此操作,并且仅在未经身份验证的情况下,通过在所有重定向上使用Rorschach120重定向中的解决方案,仅允许登录的用户访问该页面。

But this is done client side and is not that secure, because anyone can access this code from browser. 但这是在客户端完成的,并不安全,因为任何人都可以从浏览器访问此代码。

So I need that the request for my page goes to server, I tried moka 's solution in How to know if user is logged in with passport.js? 因此,我需要页面请求发送到服务器,我在如何知道用户是否使用passport.js登录时尝试了moka的解决方案 :

In app.js : app.js中

app.get('/restricted', loggedIn, function(req, res, next) {
// req.user - will exist
// load user orders and render them
});

where the loggedIn() function checks if user is logged in or not. 其中loggedIn()函数检查用户是否已登录。

But this middleware is NEVER called and anyone can still access the "restricted" page. 但是从来没有调用过这种中间件,任何人都仍然可以访问“受限”页面。 What can I do, so that this gets called? 我该怎么办,这样才能被调用?

I am new to AngularJS and NodeJS. 我是AngularJS和NodeJS的新手。 Am I doing something wrong here? 我在这里做错什么了吗? Any help will be appreciated. 任何帮助将不胜感激。

You can use middleware for that purpose. 您可以为此目的使用中间件。

app.get('/secure-route', secureMiddleware, myMethod)

let secureMiddleware = function(req, res, next) {

    authCheck(...)
        .then(function(result) {
            // pass
            next()
        })
        .catch(function(err) {
            res.status(401).json({
                code: 401,
                message: 'restricted route'
            })
        })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM