javascript - Angular - 身份验证服务

标签 javascript angularjs authentication

我是 Angular 的新手,我想知道如何创建 AuthenticationService 来检查用户是否经过身份验证。我有一些路由,我希望用户经过身份验证以便能够看到它们,如果没有经过身份验证,它们将被重定向到登录页面。我正在使用satellizer用于基于 token 的身份验证。

这是我的 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');
});

还有我的 Controller :

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 以从本地存储中删除用户和 token ,但我仍然没有被重定向到登录页面:

我的 Controller :

.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');
    });
  }
});

最佳答案

如果您使用卫星发射器,它已经为您处理好了。

使用 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 处理程序会在每次路由更改时启动,检查路由是否设置了 requireAuth,以及 isAuthenticated 是否返回 true 或 false 并相应地执行操作。

如果您想自己执行此操作,这里有一个关于如何解码 token 并检查其是否有效的很好的教程: https://thinkster.io/angularjs-jwt-auth

关于javascript - Angular - 身份验证服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37789155/

相关文章:

sql - 如何通过 WCF 连接到另一台虚拟机上的数据库?

javascript - jquery,性能方面什么是更快的 getElementById 或 jquery 选择器?

javascript - 使用 Konacha/Poltergeist(和 Rails)测试点击事件

javascript - 遍历 List 元素以构建一个数组以在 AJAX 请求中传递

javascript - React 中的内联 CSS - 如何设置多个 li 元素的样式

javascript - 来自 JSON 的每个元素的动态 CSS

javascript - AngularJS 解析函数超时

api - Binance API key

javascript - 函数调用后虚拟数组值未填充

windows - 无法从 IE 中找到凭据导致 HDFS WebUI Kerberos 身份验证失败