简体   繁体   English

如何在 AngularJS 中存储用户会话?

[英]How to store user session in AngularJS?

I have just started using AngularJS and I'm trying to store user session on my AngularApp.我刚刚开始使用 AngularJS,我正在尝试在我的 AngularApp 上存储用户会话。

First step to submit username and password works.提交用户名和密码的第一步工作。 After that, I store the username retrieved from the service in the $rootScope .之后,我将从服务中检索到的username存储在$rootScope The next page can display the username stored.下一页可以显示存储的username

But after a refresh, the $rootScope is empty.但是刷新后, $rootScope是空的。

I'm trying to do an authentication system as simple as possible.我正在尝试做一个尽可能简单的身份验证系统。

myApp.controller('loginController', ['$scope', '$rootScope', '$location', 'AuthService', '$route',
  function ($scope, $rootScope, $location, AuthService, $route) {

      $scope.login = function (credentials) {
        AuthService.login(credentials).then(function (response) {
          if(response.data == "0"){
            alert("Identifiant ou mot de passe incorrect");
          }
          else {
            // response.data is the JSON below 
            $rootScope.credentials = response.data;           
            $location.path("/");
          }
        });
      };

}]);

AuthService.login() makes a $http request. AuthService.login()发出$http请求。

JSON JSON

 {user_id: 1, user_name: "u1", user_display_name: "Steffi"} 

HTML : HTML :

 <div>Welcome {{ credentials.user_display_name }}!</div>

I tried a lot of tutorials, but I can't make session work.我尝试了很多教程,但我无法使会话工作。 I already used UserApp but it's not ok to me.我已经使用过 UserApp,但对我来说不太好。 I would like to create my own simple authentication.我想创建自己的简单身份验证。

You can use您可以使用

ngStorage ngStorage

An AngularJS module that makes Web Storage working in the Angular Way.一个 AngularJS 模块,使 Web 存储以 Angular 方式工作。 Contains two services: $localStorage and $sessionStorage.包含两个服务:$localStorage 和 $sessionStorage。

Differences with Other Implementations与其他实现的区别

No Getter 'n' Setter Bullshit - Right from AngularJS homepage: "Unlike other frameworks, there is no need to [...] wrap the model in accessors methods. Just plain old JavaScript here."没有 Getter 'n' Setter Bullshit - 来自 AngularJS 主页:“与其他框架不同,不需要 [...] 将模型包装在访问器方法中。这里只是普通的旧 JavaScript。” Now you can enjoy the same benefit while achieving data persistence with Web Storage.现在,您可以在使用 Web Storage 实现数据持久性的同时享受同样的好处。

sessionStorage - We got this often-overlooked buddy covered. sessionStorage - 我们得到了这个经常被忽视的伙伴。

Cleanly-Authored Code - Written in the Angular Way, well-structured with testability in mind.干净编写的代码- 以 Angular 方式编写,结构良好,并考虑到可测试性。

No Cookie Fallback - With Web Storage being readily available in all the browsers AngularJS officially supports, such fallback is largely redundant.无 Cookie 回退- 由于 Web 存储在 AngularJS 正式支持的所有浏览器中都可用,因此这种回退在很大程度上是多余的。

A sample example is shown below示例示例如下所示

Working Demo工作演示

var eS = angular.module('exampleStore', ['localStorage']);

$rootScope will always reset when the page refreshes, since it's a single-page app. $rootScope将在页面刷新时始终重置,因为它是一个单页面应用程序。

You need to use something that persists client-side, such as a cookie or sessionStorage (as they both have an expiration time).您需要使用客户端持久化的东西,例如 cookie 或 sessionStorage(因为它们都有一个过期时间)。 Take a look at the documentation for $cookieStore : https://docs.angularjs.org/api/ngCookies/service/$cookieStore查看$cookieStore的文档: https : $cookieStore

Remember, sensitive session information should be encrypted.请记住,敏感的会话信息应该被加密。

You need to create an api on your server to collect current user.您需要在您的服务器上创建一个 api 来收集当前用户。 This api must return the same user object as the one you have after you logged in.这个 api 必须返回与您登录后的用户对象相同的用户对象。

For every $route.path you want to secure inside $routeProvider, call this api in the controller using ng-init.对于您想要在 $routeProvider 中保护的每个 $route.path,请使用 ng-init 在控制器中调用此 api。 If the api returns an object, add the object to your $rootScope, otherwise, force user to the login page.如果 api 返回一个对象,则将该对象添加到您的 $rootScope 中,否则,强制用户进入登录页面。

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

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