javascript - Angularjs 身份验证维护

标签 javascript angularjs authentication

我正在寻找最佳的架构解决方案。

我有以下 html:

<body ng-controller="individualFootprintController as $ctrl">
<div ng-hide="$ctrl.authenticated">
            <h1>Login</h1>
            With Corporate Account: <a href="/login/corporate">click here</a>
</div>

和 Controller :

function individualFootprintController($http) {
        var self = this;
        $http.get("/is_auth").success(function () {
            self.authenticated = true;
        })
            .error(function() {
                self.authenticated = false;
            }
        );
}

问题:

1) 这个 Controller 是否适合放置这个逻辑?

2) 我想要实际的“is_authenticated”值。如果我只想触发一次请求,如何实现这一点

最佳答案

据推测,后端身份验证需要某种实际 token 。 IE。您不只是在某处设置一个 true/false 标志并将其称为身份验证,但为了能够与后端通信,您需要包含用户名/密码/cookie/token 在请求中,否则请求将被拒绝。

Controller 不是存储此类内容的好地方,因为 Controller 不是永久性的。或者至少你不应该尽可能让它们永久化。此外,将 token 存储在 Controller 中不允许任何其他人访问它。

  1. 您是否登录应取决于您是否拥有有效的身份验证 token 。
  2. 此 token 必须存储在规范的位置,最适合服务。
  3. 其他服务从那里获取 token ,并根据 token 是否可用来决定应用当前是否“已登录”。

应该如何构建的粗略草图:

app.service('AuthService', function () {
    this.token = null;
});

app.service('FooService', function (AuthService, $http) {
    $http.get(..., AuthService.token, ...)
});

app.controller('LoginStatusController', function (AuthService) {
    Object.defineProperty(this, 'isLoggedIn', {
        get: function () { return AuthService.token != null; }
    });
});
<div ng-controller="LoginStatusController as ctrl">
    <div ng-hide="ctrl.isLoggedIn">

当您实际登录并获取 token 时,您设置了 AuthService.token,它将对所有其他服务和 Controller 可用。如果当 token 变得无效或未设置时,所有服务和 Controller 都会失去其经过身份验证的状态。

关于javascript - Angularjs 身份验证维护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40906532/

相关文章:

javascript - 显示文件输入标签中选择的所有图像

javascript - 如何在 NodeJs 中手动更新多个 Mongo 文档?

angularjs - 如何增加 Angular Material 中的 md-tab 大小?

angularjs - 如何在 AngularJS View 中格式化数据?

javascript - 在同级兄弟指令中进行通信的理想方式是什么?

java - 登录 局域网内计算机的用户名 java

javascript - 使用 Google 登录按钮无需服务器即可对用户进行身份验证

javascript - 如何等待 forEach 循环中的所有 Promise 添加到数组中?

authentication - 与 MediaWiki 共享 WordPress session cookie

javascript - three.js - 如何翻译几何