[英]Storing JWT token ID in $rootScope
I am working on my first angular application and using JWT to authenticate users. 我正在开发我的第一个角度应用程序,并使用JWT对用户进行身份验证。 Once the user is logged in sucessfully I am storing the token in a $rootScope object, ie 用户成功登录后,我会将令牌存储在$ rootScope对象中,即
$rootScope.sessionStorage = {
"token" : null,
"loggedIn" : false,
"userId" : null
};
I then use this when making API calls. 然后在进行API调用时使用它。
Is this a bad place to store variables that will be used across the application? 这是存储将在整个应用程序中使用的变量的不好的地方吗? I understand that the value will be lost if the user refreshes or closes the window but this isn't a problem. 我了解,如果用户刷新或关闭窗口,该值将丢失,但这不是问题。
If you're not worried about refreshing getting rid of the token, then storing it in memory is fine. 如果您不担心刷新摆脱令牌,那么将其存储在内存中就可以了。
However, if you're going to store it in memory, I think the more semantic and scalable place to store the token would be as a constant: 但是, 如果您要将其存储在内存中,我认为存储令牌的语义和可扩展性更高的位置将是一个常量:
app.constant('TOKEN', token);
$rootScope
implicitly makes things automatically available to all controllers without injection, which I don't think is what you necessarily need in this case. $rootScope
隐式使所有控制器无需注入即可自动使用所有东西,在这种情况下,我认为这不是您必需的。
You can just inject the constant where you need it (which would probably be in an interceptor): 您可以将常量注入所需的位置(可能在拦截器中):
$httpProvider.interceptors.push('myRequestInterceptor');
Your implementation of the interceptor is up to you, but normally it'll just involve patching an Authorization
header with a Bearer <token>
field. 拦截器的实现取决于您,但通常只涉及使用Bearer <token>
字段修补Authorization
标头。
Using local storage is pretty simple. 使用本地存储非常简单。 angular-storage
makes this pretty easy (it's an injectable service). angular-storage
使这变得非常容易(这是一种可注射的服务)。 The investment to instead store in local storage would be minimal compared to just storing it in memory as a constant. 与仅将其作为常量存储在内存中相比,用于存储在本地存储中的投资将是最小的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.