【问题标题】:$scope.isAuthenticated returns false after refresh page$scope.isAuthenticated 刷新页面后返回 false
【发布时间】: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 块是这样做的好地方)

标签: angularjs jwt


【解决方案1】:

您可以检查本地存储中是否有令牌,并使用服务相应地设置“isAuthenticated”的值:

$scope.isAuthenticated = AuthService.isAuthenticated();

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

【讨论】:

    猜你喜欢
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 2017-07-04
    • 2010-11-14
    • 1970-01-01
    • 2012-11-18
    相关资源
    最近更新 更多