Express.js和Angular – 身份validation和login会话

我正在使用expressjs和angularjs的应用程序。 基本上,expressjs只是返回一个具有angular度单页面应用程序的.html。 所有的路由都是使用angularjs完成的,expressjs只是暴露了一些web服务(GET,POST)。

所以,如果我只是做一个普通的expressjs应用程序,我会使用passportjs并将用户存储在服务器端的会话中。 当用户尝试访问/pipe理页面时,我会使用护照中间件来检查是否允许路由等等。 干净利落。

但是有了angular度,所有的路由都是在客户端完成的 – 甚至可以评估用户是否login了。现在当然有很多关于这方面的内容,但是几乎所有的解决scheme都在localStorage或者angular色的$cookie存储了任何types的令牌密钥。 现在我想知道 – 安全吗?

如果有人在公用计算机上运行这样的应用程序,并忘记注销,任何人都可以看到localStorage或angular的$cookie并获得令牌,对吧?

那么在客户端使用angularjs实现安全authentication的理论过程是什么?

引用:

所以,如果我只是做一个普通的expressjs应用程序,我会使用passportjs并将用户存储在服务器端的会话中。

会话数据存储在服务器上时,会话标识符存储在客户端的cookie中。 如果cookie被盗(例如在公共计算机示例中),那么该会话可以被其他人使用。 客户端应用程序可以使用cookie会话标识符scheme。 当Angular向您的服务器发出XHR请求时,它将提供cookie。

正如你所看到的,JSON Web Tokens(JWT)已经成为一种新的scheme。 他们replace会话标识符,但不是cookie。 您可能会看到正在使用本地存储,但这不是安全的。 如果您设置HttpOnly; Secure Cookie实际上是存储身份validation令牌最安全的地方HttpOnly; Secure HttpOnly; Secure标志。 这会阻止JS环境读取cookie,并阻止浏览器通过非安全通道将其发送到服务器。

我已经在这两篇文章中详细地写了关于JWT和Angular应用程序:

使用JSON Web令牌(JWT)构build安全的用户界面

基于令牌的单页面应用validation(SPA)

如果您担心公用计算机,则必须避免将令牌存储在一起。 这意味着将令牌保留在JavaScript内存中,并通过HTTP标头(通常为Authorization: Bearer <access_tken> )提供。 只要选项卡closures,令牌就会丢失,会话已经结束。 当然,这要求用户closures标签,所以你可以更进一步,在你的令牌上设置一个非常低的“空闲时间”,比如5分钟。 如果用户在五分钟内没有使用令牌,则认为该令牌有效,必须重新login。

PS我在Stormpath工作,我们有一个用户pipe理服务,这使得添加validation到你的Angular应用程序非常容易。 你可以在我们的AngularJS指南中阅读

我通过创build一个名为MyAuthentication的Angular Service来完成这个任务,它提供了这些方法

  • validation(un,pwd)
  • 登出()

为了得到适当的分离我有一个单独的用户代理,使我的用户HTTP请求。

 angular.module('myNgApplication').service('MyAuthentication', function ($rootScope, $cookies, $log, UserProxy) { var self = this; self.user = null ; (function(){ UserProxy.retrieveSession().then(function(authResponse){ self.user = authResponse }, function() { self.user = null }) }).call(this) this.isLoggedIn = function() { return self.user != null ; } this.login = function (email, password) { return UserProxy.login(email, password).then(function(authResponse){ self.user = authResponse return self.user }) } this.logout = function () { return UserProxy.logout().then(function(response){ self.user = null ; return response }) } // this is never used externally. because the HTTP request to gte the user may be in progress when this is called and therefore self.user is null this.getUser = function() { return self.user } this.bootstrapUser = function(callback){ if(self.isLoggedIn()){ callback(self.user) } else { $rootScope.$watch(self.getUser, function(newUser, oldUser) { if(newUser != oldUser) { callback(self.user) } }); } } }) 

用户对象始终保持在内存中……然后,授权可能看起来像这样:

 angular.module('myNgApplication').service('MyEntitlments', function (MyAuthentication) { this.isEntitled = function(feature) { return MyAuthentication.bootstrapUser(function(user){ // check users role and feature return true || false }) } }) 

并在服务器上,我仍然使用护照。