Architecture for login system on MEAN stack?

走远了吗. 提交于 2019-12-20 08:46:21

问题


I'm developing a web app on the MEAN stack (MongoDB, Express, AngularJS, and node.js). I'm developing a login system, and will also have some of the Angular routes protected so that only logged-in users can access them. I'm trying to think of the best way to approach the architecture of this.

I'm thinking of the current workflow:

  • User logs in via AngularJS form, which sends an http POST to an Express endpoint. The endpoint validates the user against the database, and responds with an OAuth token as well as a cookie. Both are stored in the mongo database for later validation.
  • Once AngularJS receives the login response, it stores the received cookie using ng-cookies, and stores the OAuth token in a User service.
  • Every time the route changes in AngularJS now, the User service is used to make sure that the cookie is still legitimate by comparing it to cookies in the mongo database (this would be an API call using Angular's resolve... would this create a noticeable lag?)
  • When a user clicks "log out" or the cookie expires, the cookie and OAuth token are both deleted from the database and will no longer be valid.

Does this approach make sense? Is it secure, and will it be relatively efficient/quick in execution?


回答1:


I ended up combining my original workflow with Express's auth example, seen here. It is as follows:

  • When user initially loads the app, an http call is made to an Express endpoint that checks if a session exists already for the user. If so, the user is stored in $rootScope and considered logged in.
  • Any time the AngularJS route changes, the same endpoint is accessed. Route protection was specified in a way similar to that described here. If the endpoint ever returns that no session exists, $rootScope.user is unset (if it needs to be), and the user is redirected to the login page.
  • When the login form is processed, it posts to an Express endpoint. The endpoint retrieves the user from the mongoDB (if it exists), and attempts to hash the password. If it's a match, the user's session is set, stored in the mongo DB, and the endpoint returns the user object (used to store in the $rootScope as previously mentioned).
  • Any time any further endpoints are accessed, the functions are first passed through the restrict function which ensures that a session exists before sending any data to the client. It returns a 401 if no session exists, which is then handled on the Angular side using this HTTP interceptor to unset $rootScope.user and redirect to the login screen.
  • When the user clicks "log out" on the Angular side, the session is unset and deleted from the mongo DB, $rootScope.user is set to null, and the user is redirected back to the front page.


来源:https://stackoverflow.com/questions/19185315/architecture-for-login-system-on-mean-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!