【发布时间】:2015-03-19 09:55:58
【问题描述】:
我正在使用 JWT 管理身份验证。我正在尝试使用 ng-show 在我的导航中显示/隐藏登录和注销按钮。它工作正常,但是在我刷新页面后看起来我不再登录了,变量 $scope.isAuthenticated 在刷新后返回 false,我怎样才能在我登录时保持 $scope.isAuthenticated 为真??
app.js
myApp.controller('UserCtrl', function ($scope, $http, $window) {
$scope.user = {username: '', password: ''};
$scope.isAuthenticated = false;
$scope.welcome = '';
$scope.message = '';
$scope.submit = function () {
$http
.post('/authenticate', $scope.user)
.success(function (data, status, headers, config) {
$window.sessionStorage.token = data.token;
$scope.isAuthenticated = true;
var encodedProfile = data.token.split('.')[1];
var profile = JSON.parse(url_base64_decode(encodedProfile));
$scope.welcome = 'Welcome ' + profile.first_name ;
$scope.error = '';
})
.error(function (data, status, headers, config) {
delete $window.sessionStorage.token;
$scope.error = 'Error: Invalid user or password';
$scope.welcome = '';
});
};
$scope.logout = function () {
$scope.welcome = '';
$scope.message = '';
$scope.isAuthenticated = false;
delete $window.sessionStorage.token;
};
});
index.html
<div ng-controller="UserCtrl">
<span ng-show="isAuthenticated">{{welcome}}</span>
<form ng-show="!isAuthenticated" ng-submit="submit()">
<input ng-model="user.username" type="text" name="user" placeholder="Username" />
<input ng-model="user.password" type="password" name="pass" placeholder="Password" />
<input type="submit" value="Login" />
</form>
<div ng-if="error" class="alert alert-danger"> {{error}}</div>
<div ng-show="isAuthenticated">
<a ng-click="callRestricted()" href="">Shh, this is private!</a>
<br>
<div>{{message}}</div>
<a ng-click="logout()" href="">Logout</a>
</div>
</div>
【问题讨论】:
-
您需要以某种方式保存“已验证”状态(本地存储、cookie 等)并在首次加载时读取它(您的主模块的
run块是这样做的好地方)