使用AngularJS和ui-router实现身份验证

时间:2016-04-06 19:45:18

标签: angularjs authentication angular-ui-router

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

  • if(用户未经过身份验证&&状态需要身份验证) 去登录'州
  • else if(用户已通过身份验证&&状态不需要身份验证),然后是 去主要'州
  • 否则转到用户请求的状态。

我已经以一种我不确定是正确的方式实现它,我需要你们的一些验证。

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

但据我所知,这些信息只能在$ stateChangeSuccess中使用,而不能在$ stateChangeStart中获得,因此如果我在$ stateChangeSucceess中实现上面写的逻辑,那么在转换结束之前,某些页面会闪烁。

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

感谢。

2 个答案:

答案 0 :(得分:0)

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

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

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

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

答案 1 :(得分:0)

在您的模块中使用run函数,并结合一个知道用户是否经过身份验证的服务:

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')*/

    });

}

此功能将始终执行状态更改。