javascript - 如何在 AngularJS 中存储用户 session ?

标签 javascript angularjs authentication session cookies

我刚刚开始使用 AngularJS,我正在尝试将用户 session 存储在我的 AngularApp 上。

提交用户名和密码的第一步有效。 之后,我将从服务中检索到的 username 存储在 $rootScope 中。 下一页可以显示存储的用户名

但是在刷新之后,$rootScope 是空的。

我正在尝试做一个尽可能简单的身份验证系统。

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() 发出一个 $http 请求。

JSON

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

HTML:

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

我尝试了很多教程,但我无法使 session 正常工作。 我已经使用过 UserApp,但它对我来说不好。我想创建自己的简单身份验证。

最佳答案

你可以使用

ngStorage

An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage and $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." Now you can enjoy the same benefit while achieving data persistence with Web Storage.

sessionStorage - We got this often-overlooked buddy covered.

Cleanly-Authored Code - Written in the Angular Way, well-structured with testability in mind.

No Cookie Fallback - With Web Storage being readily available in all the browsers AngularJS officially supports, such fallback is largely redundant.

示例如下所示

Working Demo

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

关于javascript - 如何在 AngularJS 中存储用户 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23682511/

相关文章:

javascript - 在 Angular 中混合 javascript 和 typescript 时出错

authentication - Meteor.js 中的自定义身份验证

javascript - 从 Flash 调用 javascript 函数

javascript - 弹出键盘时向上滚动文本字段

javascript - 卸载组件时对 setState 发出警告

javascript - 通过 DOM 获取页面的内容类型

javascript - angularjs - ngRoute 无法正常工作

javascript - 如何在Angular JS中获取id值

ruby-on-rails-3 - 如何使用 DEVISE 的 session[:user. return_to]

authentication - 如何为 JWT token 生命周期验证添加额外检查?