【问题标题】:Proper way to handle authentication处理身份验证的正确方法
【发布时间】:2014-04-15 14:49:06
【问题描述】:

我已经阅读了很多关于如何在 Angular 应用程序中实现身份验证的不同示例。我使用Firebase Simple Login 作为(无)后端。

用户只有在登录后才能看到我的应用程序的任何内容。如果他们退出,他们只能看到/auth/login/auth/register。目前,我有以下可行的解决方案。但是:

1) 我不确定这是否是防弹的,因为...

2) ...当我在未登录的情况下手动打开/home 时,我正确地被重定向到/auth/login,但HomeCtrl 无论如何都会被执行。没有敏感数据暴露,因为后端没有返回数据,但是如果我退出,必须有一种方法根本不执行控制器?

3) 每次我暴露敏感数据时,是否必须检查控制器内部是否一遍又一遍地验证用户身份?

额外问题:成功登录后如何重定向到/home?目前,在我的 AuthService 中,我在成功登录时执行 $location.path('home');,但这不考虑状态?!

我的 app.js:

angular.module('myApp', ['ionic', 'firebase', 'myApp.services', 'myApp.controllers'])

.run(function($rootScope, $location, AuthService) {
  $rootScope.$on('$stateChangeStart', function (ev, to, toParams, from, fromParams) {     

  /**
   * AuthService.isLoggedIn() returns TRUE or FALSE
   * depending on whether user authenticated successfully 
   * against the Firebase backend
   */

    // redirect to login 
    if (!AuthService.isLoggedIn() && to.name !== 'auth.register') {
      $location.path('/auth/login');
    }
  });
})

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

  $stateProvider

    .state('auth', {
      url: "/auth",
      abstract: true,
      templateUrl: "templates/auth-tabs.html",
      controller: 'AuthCtrl'
    })

    .state('auth.login', {
      url: '/login',
      views: {
        'login-tab': {
          templateUrl: 'templates/auth-login.html'
        }
      }
    })

    .state('auth.register', {
      url: '/register',
      views: {
        'register-tab': {
          templateUrl: 'templates/auth-register.html'
        }
      }
    })

    .state('home', {
      url: '/home',
      templateUrl: 'templates/home.html',
      controller: 'HomeCtrl'
    });

  $urlRouterProvider.otherwise('/home');

});

【问题讨论】:

  • angularFire-seed 有一个可用的路由器/登录系统,以及一个可以与 ngRoute 一起使用的插件模块。您应该能够在那里获得一些想法(或只是使用它)。

标签: angularjs authentication firebase firebase-security


【解决方案1】:

我实现它的方式是处理401 http 服务器响应,因为我不想担心检查用户身份验证状态,我更喜欢让服务器来处理。话虽如此。

$urlRouter.sync() 上的文档指定如果您阻止默认事件,您可以手动触发succesChange

angular.module('app', ['ui.router']);
  .run(function($rootScope, $urlRouter) {
    $rootScope.$on('$locationChangeSuccess', function(evt) {
      // Halt state change from even starting
      evt.preventDefault();
      // Perform custom logic
      var meetsRequirement = ...
      // Continue with the update and state transition if logic allows
      if (meetsRequirement) $urlRouter.sync();
    });
});

$urlRouter documentation

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 1970-01-01
    • 2020-06-25
    • 2020-05-29
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    相关资源
    最近更新 更多