$ scope.isAuthenticated在刷新页面后返回false

时间:2015-01-21 00:42:39

标签: angularjs jwt

我正在使用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>

1 个答案:

答案 0 :(得分:1)

您可以检查本地存储中是否有令牌,并设置&#34; isAuthenticated&#34;相应地使用服务:

$scope.isAuthenticated = AuthService.isAuthenticated();

然后,AuthService负责检查本地存储中是否有令牌。