javascript - 使用应用程序级别解析 AngularJS 的动态指令模板

标签 javascript angularjs authentication local-storage

目前,我正在使用 AngularJS 和 REST API 作为后端服务来实现完全无状态的基于 token 的身份验证。这工作得很好,但关于一种状态我目前不知道,想问你如何处理它。

我的目的只是将我的身份验证 token 从客户端保存到本地存储中。在从应用程序初始加载时,我想从 REST API (GET/me) 检索所有用户信息,并将其保存在我的 AngularJS 项目的 $scope 中。

实现后,我遇到了几个问题,以确保检索到的用户信息得到完全解决并且可以使用这些信息(例如用户的访问权限)。

我只是想让你展示一个我遇到一种“异步问题”的例子。

angular.directive('myDirective', ['MyAsyncService', function(MyAsyncService) {
  return {
    restrict: 'E',
    templateUrl: function(element, attributes) {
      console.log(MyAsyncService.getData());
    } 
  }
}]

在此示例中,当呈现指令时,我的异步服务还没有信息。另外,从 ngRoute/ui-router 的解析函数中检索异步数据或从 AngularJS 的 run() 方法中检索异步数据也无法解决我的问题。

回到我的问题...最好在客户端保存一些用户信息以避免出现一些问题?从我的 Angular 来看,出于安全考虑,最好不要保存任何类型的用户信息(如访问权限、用户名、ID、电子邮件地址……)。

如何在基于 token 的 AngularJS 应用程序中处理身份验证和授权?

预先感谢您,希望您能让我重回正轨。

最佳答案

您需要resolve()身份验证 - 特别是应用程序级别的这种类型的身份验证。

如果您没有使用ui.router - 看看。

当我们在路线上 resolve() 时,我们所说的是 - 在这个东西完成它正在做的事情之前不要做任何其他事情。

这还假设您熟悉 promise 。

您的解析依赖项最终会期望此异步请求返回一个 promise ,以便在回调完成执行后它可以链接 Controller 逻辑。

例如:

$stateProvider
  .state('myState', {
    resolve:{
      auth:  function($http){
        // $http returns a promise for the url data
        return $http({method: 'GET', url: '/myauth'});
      }
    },
    controller: function($scope, auth){
      $scope.simple = auth;
    }
});

但还有更多。如果您希望在任何路由的应用程序执行开始时进行解析 - 您还需要链接您的状态声明:

$stateProvider
  .state('app', {
    abstract: true,
    templateUrl: 'app/views/app.tpl.html',
    resolve:{
      auth:  function($http){
        // $http returns a promise for the url data
        return $http({method: 'GET', url: '/myauth'});
      }
    },
    controller: function($scope, auth){
      $scope.resolvedauth = auth;
    }
  }
  .state('app.home', {
    url: '/home',
    templateUrl: 'home/views/home.tpl.html',
    controller: function($scope){
      //Should be available.
      console.log($scope.$parent.resolvedauth);
    }
  });

既然您的 child 继承了应用程序级别解析,您可以通过执行以下操作来控制模板:

.directive('myDirective', function() {
  return {
    templateUrl: function(elem, attr){
      return 'myDirective.'+attr.auth+'.html';
    }
  };
});

以及声明本身:

<my-directive auth="resolvedauth.status" />

关于javascript - 使用应用程序级别解析 AngularJS 的动态指令模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26642746/

相关文章:

javascript - Angular $http.get 不工作

angularjs - 有效识别元素 - AngularJS Automation with Ranorex

c# - 如何使用 Azure 函数后端保护静态客户端 Blazor 应用程序?

python - Colaboratory - 记住 Google Drive Auth(Python)

vb6 - 更新: Interacting with the user on the windows logon screen

Javascript - 字符串连接

javascript - 在Javascript中获取XML节点的textContent

javascript - 如何在 AngularJS 中排序时删除重复值?

javascript - Webkit 和 Mozilla 改变滚动条

javascript - 为什么我的 eval 没有将 json 字符串转换为对象