首页 > Angular中怎么处理安全性?

Angular中怎么处理安全性?

我怎么在页面中让用户不能做出超过等级的操作和访问?


方法太多,看你的项目规模和系统设计了,如果要限制接口权限(如OAuth2),可以考虑下面这种:

app.factory('authInterceptor', function($q, $cookieStore, $location) {
  return {
    request: function(config) {
      config.headers = config.headers || {};
      if ($cookieStore.get('token')) {
        config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
      }
      return config;
    },
    responseError: function(response) {
      if (response.status === 401) {
        $location.path('/login');
        $cookieStore.remove('token');
      }
      return $q.reject(response);
    }
  };
});

$httpProvider.interceptors.push('authInterceptor');

如果是路由权限,那么对上面的代码稍加修改,通过判断session也是可以实现的。
如果你用了ui-router,可以考虑在app.js中加入这句:

$rootScope.$on('$stateChangeStart', function(event, next) {
  return Auth.isLoggedInAsync(function(loggedIn) {
    if (next.authenticate && !loggedIn) {
      return $location.path("/login");
    }
  });
});

具体Auth类中怎么实现或许可以参考另一篇文章:
http://blog.coding.net/blog/techniques-for-authentication-in-angular-j...

【热门文章】
【热门文章】