简体   繁体   English

在AngularJS中保留身份验证令牌

[英]Persisting authentication token in AngularJS

I'm building an AngularJS application that interacts with an API that uses authentication tokens to authenticate users. 我正在构建一个AngularJS应用程序,该应用程序与使用身份验证令牌对用户进行身份验证的API进行交互。 Everything seems to be working fine, but I'm struggling with a way to properly persist the authentication token between requests. 一切似乎都运行良好,但我正在努力在请求之间正确地保持身份验证令牌。

At the moment, when a user logs in with correct credentials an authToken is returned, and I'm setting that on $rootScope.authToken . 目前,当用户使用正确的凭据登录时,将返回authToken ,并且我将其设置$rootScope.authToken I'm also sending that auth token for future requests, but if I do a hard reload reload the webpage with F5 $rootScope gets cleared and I have to authenticate again. 我也在为将来的请求发送该身份验证令牌,但是如果我重新加载重新加载网页,请使用F5 $rootScope清除,我必须再次进行身份验证。

I'm aware I can store the authToken in a cookie, but would that be the most secure way? 我知道我可以将authToken存储在cookie中,但这是最安全的方式吗? Am I better off using local storage to store the token? 我最好使用本地存储来存储令牌吗? If local storage is used, would that not get cleared when the user restarts their browser? 如果使用本地存储,当用户重新启动浏览器时,是否会清除? I'd ideally like the login to persist for a few days. 我理想情况下登录要坚持几天。

Firstly, I'm not sure what the format of your authToken is but localStorage should not be used for any sensitive data. 首先,我不确定你的authToken的格式是什么,但localStorage不应该用于任何敏感数据。 Using localStorage works great (and survives browser restarts) as long as your authToken is relatively tamper-proof either through some form of encryption or nonce. 只要您的authToken通过某种形式的加密或随机数进行相对防篡改,使用localStorage可以很好地工作(并且可以保持浏览器重启)。

Essentially, you should be careful that since the value is "visible" to all client-side users it should be assumed to be possible to modify or increment. 基本上,您应该小心,因为值对所有客户端用户“可见”,应该假定可以修改或增加。

Have you thought about revocation of login sessions? 您是否考虑过撤销登录会话? For example, if you want to log out all active sessions of your application, how would you do it? 例如,如果要注销应用程序的所有活动会话,您将如何执行此操作? Since the authToken is stored client-side, you may need to add a timestamp (or some other unique value) to it that can be checked server-side. 由于authToken存储在客户端,因此您可能需要向服务器端添加时间戳(或其他一些唯一值)。

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

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