gpt4 book ai didi

javascript - Angularjs 身份验证维护

转载 作者:行者123 更新时间:2023-12-01 01:24:30 26 4
gpt4 key购买 nike

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

我有以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com