How to store an auth token in an Angular app

£可爱£侵袭症+ 提交于 2019-12-03 05:10:23

If you are looking for something that will definitely not persist then I would simply keep the token in memory and not rely on the browser for storage. However storing inside rootScope would not be best practice.

I would recommend that you wrap your server access code in an Angular Service if you have not done so already. You can then encapsulate your token within that Service at runtime (e.g. as a property) without worrying about having to access it when calling from other parts of your application.

Angular Services are singleton so your "server service" will be a global instance that can be accessed using normal dependency injection.

$window.sessionStorage is the way to go unless you're targeting very old browsers.

According to www.w3schools.com sessionStorage is supported from IE 8.0, Chrome 4.0, Firefox 3.5, and Safari 4.0.

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