【问题标题】:Angular - authentication serviceAngular - 身份验证服务
【发布时间】:2016-06-13 11:52:42
【问题描述】:

我是 Angular 的新手,我想知道如何制作一个 AuthenticationService 来检查用户是否经过身份验证。我有路由,我希望用户对其进行身份验证以便能够看到它们,如果它们未通过身份验证,它们将被重定向到登录页面。我正在使用satellizer 进行基于令牌的身份验证。

这是我的 app.js

angular.module('coop', ['ionic', 'coop.controllers', 'coop.services', 'satellizer'])

.constant('ApiEndpoint', {
  url: 'http://coop.app/api'
})

.run(function($ionicPlatform, $rootScope, $auth, $state, $location) {

  // Check for login status when changing page URL
  $rootScope.$on('$routeChangeStart', function (event, next) {
      var currentRoute = next.$$route;

      if (!currentRoute || currentRoute.requiresAuth && !AuthenticationService.authenticated) {
        $location.path('/auth');
      }
      else if (!currentRoute || !currentRoute.requiresAuth && AuthenticationService.authenticated) {
        $location.path('/front');
      }
  });

  $rootScope.logout = function() {

      $auth.logout().then(function() {

          // Remove the authenticated user from local storage
          localStorage.removeItem('user');

          // Remove the current user info from rootscope
          $rootScope.currentUser = null;
          $state.go('main.auth');
      });
    }

  $rootScope.token = localStorage.getItem('token');

  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      // StatusBar.styleDefault();
      StatusBar.show();
      StatusBar.overlaysWebView(false);
      StatusBar.styleLightContent();
      StatusBar.backgroundColorByHexString("#2a2e34");
    }
  });
})

.config(function($stateProvider, $urlRouterProvider, $authProvider, ApiEndpoint) {

  $authProvider.loginUrl = ApiEndpoint.url + '/authenticate';

  $stateProvider
  .state('main', {
    url: '/main',
    abstract: true,
    templateUrl: 'templates/main.html',
    requiresAuth: true
  })

  .state('main.auth', {
    url: '/auth',
    views: {
      'content': {
        templateUrl: 'templates/login.html',
        controller: 'AuthController',
        requiresAuth: false
      }
    }
  })

  .state('main.front', {
    url: '/front',
    views: {
      'content': {
        templateUrl: 'templates/main-front.html',
        controller: 'FrontPageController',
        requiresAuth: true
      }
    }
  })

  .state('main.article', {
    url: '/article/{id}',
    views: {
      'content': {
        templateUrl: 'templates/main-article.html',
        controller: 'ArticleController',
        requiresAuth: true
      }
    }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/main/front');
});

还有我的控制器:

angular.module('coop.controllers', [])

.controller('FrontPageController', function($scope, ArticleService, $state) {
  ArticleService.all().then(function(data){
    $scope.articles = data;
    $scope.like = function(article){
      article.like = article.like == 0 ? 1 : 0;
      ArticleService.like(article.id, article.like)
    };
  })
})

.controller('ArticleController', function($scope, ArticleService, $stateParams, $ionicSlideBoxDelegate, $auth) {
  ArticleService.get($stateParams.id).then(function(response) {
    $scope.article = response;
    $scope.commentsCount = response.comments.length;
    $scope.articleText = response.text;

    $scope.like = function(){
      $scope.article.like = $scope.article.like == 0 ? 1 : 0;
      ArticleService.like($scope.article.id, $scope.article.like)
    };

    $ionicSlideBoxDelegate.update();
  })

})

.controller('AuthController', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) {
    $scope.loginData = {}
    $scope.loginError = false;
    $scope.loginErrorText;

    $scope.login = function() {
        var credentials = {
            email: $scope.loginData.email,
            password: $scope.loginData.password
        }

        $auth.login(credentials).then(function(response) {
            var token = JSON.stringify();
            localStorage.setItem('token', response.data.token);

            $ionicHistory.nextViewOptions({
              disableBack: true
            });

            $state.go('main.front');
        }, function(){
            $scope.loginError = true;
            $scope.loginErrorText = error.data.error;
        });
    }
});

更新代码

我已按照建议更改了 app.js:

// Check for login status when changing page URL
  $rootScope.$on('$routeChangeStart', function (event, next) {
    var currentRoute = next.$$route;

    if (!currentRoute || currentRoute.requiresAuth && !$auth.isAuthenticated()) {
      $location.path('/main/login');
    }
    else if (!currentRoute || !currentRoute.requiresAuth && $auth.isAuthenticated()) {
      $location.path('/main/front');
    }
  });

并添加了注销控制器以从本地存储中删除用户和令牌,但我仍然没有被重定向到登录页面:

我的控制器:

.controller('AuthController', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) {
  $scope.loginData = {}
  $scope.loginError = false;
  $scope.loginErrorText;

  $scope.login = function() {
    var credentials = {
        email: $scope.loginData.email,
        password: $scope.loginData.password
    }

    $auth.login(credentials).then(function(response) {
        var token = JSON.stringify();
        localStorage.setItem('token', response.data.token);

        $ionicHistory.nextViewOptions({
          disableBack: true
        });

        $state.go('main.front');
    }, function(){
        $scope.loginError = true;
        $scope.loginErrorText = error.data.error;
    });
  }

  $scope.logout = function() {
    $auth.logout().then(function() {
      // Remove the authenticated user from local storage
      localStorage.removeItem('user');
      localStorage.removeItem('token');

      // Remove the current user info from rootscope
      $rootScope.currentUser = null;
      $state.go('main.login');
    });
  }
});

【问题讨论】:

    标签: javascript angularjs authentication


    【解决方案1】:

    如果您使用的是 satellizer,它已经为您解决了这个问题。

    使用 satelizer 的 $auth 服务的 isAuthenticated() 方法,而不是自己定义

    $rootScope.$on('$routeChangeStart', function (event, next) {
      var currentRoute = next.$$route;
    
      if (!currentRoute || currentRoute.requiresAuth && !$auth.isAuthenticated()) {
        $location.path('/auth');
      }
      else if (!currentRoute || !currentRoute.requiresAuth && $auth.isAuthenticated()) {
        $location.path('/front');
      }
    

    });

    $auth.isAuthenticated() 的作用基本上是检查用户是否保存了有效的 jwt,并返回 true 或 false。

    $routeChangeStart 处理程序在每次路由更改时启动,检查路由是否设置了 requiresAuth 以及 isAuthenticated 是否返回 true 或 false 并采取相应措施。

    如果你想自己做,这里有一个很好的教程,介绍如何解码令牌并检查它是否有效: https://thinkster.io/angularjs-jwt-auth

    【讨论】:

    • 我认为你的建议是完美的,我已经按照你说的做了,但是当我转到我的主页/首页时,我仍然没有被重定向到登录页面。
    • 如果您之前登录过并且没有注销,您可能需要手动从本地存储中删除令牌。
    • 另外,在您的 AuthController 中,如果您需要手动设置令牌,请使用 satellizer 的 $auth.setToken() 而不是 localStorage.setItem(),但如果我没记错的话 $login 会设置它自动为您服务。
    • 我已经更新了我的代码,并尝试在注销后对其进行测试,但是当我转到一些要求用户进行身份验证的页面时,我仍然没有被重定向
    • 有点超出范围,这里有一些想法: - 不要使用 localStorage.removeItem('user') 或直接操作 localstorage,satellizer 有类似 $auth.logout() 的方法。它是window.localStorage。 - 使用 chrome 开发工具或类似工具检查您的令牌是否在登录和注销后在本地存储中创建和销毁 - 在 $location.path 附近添加 console.logs 以查看是否在需要时在代码中到达那里 - 使用 event.preventDefault( ) 在 routeChangeStart 上当您想要阻止原始导航尝试时 -plunker 如果您需要更多帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2020-08-13
    • 2017-06-11
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多