【问题标题】:Implementing authentication with AngularJS and ui-router使用 AngularJS 和 ui-router 实现身份验证
【发布时间】:2016-07-27 10:28:29
【问题描述】:

我正在尝试使用 ui-router 和 angularJS 处理身份验证,我想实现以下正常情况:

  • 如果(用户未通过身份验证 && 状态需要身份验证)则 进入“登录”状态
  • else if (用户已通过身份验证 && 状态不需要身份验证) then
    进入“主要”状态
  • 否则转到用户请求的状态。

我以一种我不确定是否正确的方式实现了它,我需要你们在这里进行一些验证。

我有一个解析函数,用于检索用户是否从服务器进行身份验证的信息,如果它被拒绝,那么我将用户发送到 $stateChangeError 中的“登录”状态。如果它解决了,我会处理 $stateChangeSuccess 中的其他逻辑。

但据我了解,该信息仅在 $stateChangeSuccess 中可用,而在 $stateChangeStart 中不可用,因此,如果我在 $stateChangeSuccesses 中实现上面编写的逻辑,则某些页面将在过渡结束前闪烁。

请指教。有没有其他方法或方法来改进这个解决方案?我想为每个状态制作一个解析功能,检查用户是否经过身份验证并在那里进行路由。

谢谢。

【问题讨论】:

    标签: angularjs authentication angular-ui-router


    【解决方案1】:

    这是单页应用程序的问题。我在我的角度页面中使用的解决方案之一是缓存用户 ID 以及用户在本地存储中经过身份验证的事实。您也可以为此添加到期时间。这是本地存储模块的链接:https://github.com/grevory/angular-local-storage(还有其他的)。

    然后在每个状态下,您都可以检查用户是否已经通过身份验证,而不是每次都返回服务器。此外,这将有助于后退/前进按钮更好地工作。通常在您的控制器中,您将有代码来检查用户是否经过身份验证(这可能会检查本地存储中的标志并获取最初从服务器检索的用户信息)。

    如果浏览器被多个用户共享,我会看到一些安全问题。

    这篇文章似乎列出了一种更好/更新的方法:https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

    【讨论】:

      【解决方案2】:

      在您的模块中使用runfunction 与知道用户是否已通过身份验证的服务相结合:

      angular
        .module('myApp')
        .run(runFn);
      runFn.$inject = ['$rootScope', 'MyAuthService', '$state'];
      function runFn($rootScope, MyAuthService, $state){
      
         $rootScope.$on('$stateChangeSuccess', function(e, toState, toParams, fromState, fromParams) {
      
                var userAuthenticated =   MyAuthService.isLogged();
      
                //* check if the user it's present on cookies
                //if(!userAuthenticated && $cookieStore.get('user_token'))
                //  If the token is in the cookies i get the user from server
                //else
                // $state.go('login')
      
                //your logic here
                /*if (user is not authenticated && state requires authentication) then $state.go('login')*/
      
          });
      
      }
      

      这个函数会在状态改变时执行。

      【讨论】:

      • 谢谢。当我执行您提到的“var userAuthenticated = MyAuthService.isLogged();”行时,如何确定服务 MyAuthService 保存了用户是否登录的信息?目前我正在发送一个 api 调用来检查这一点。还有其他方法吗?
      • 一般来说,我为此使用cookies。检查我编辑的答案。为了更清楚,阅读这篇优秀的文章scotch.io/tutorials/…
      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      相关资源
      最近更新 更多