search

Home  >  Q&A  >  body text

angular.js - Angular中怎么处理安全性?

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

曾经蜡笔没有小新曾经蜡笔没有小新2743 days ago565

reply all(1)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-15 16:52:50

    There are too many methods. It depends on your project scale and system design. If you want to limit interface permissions (such as OAuth2), you can consider the following:

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

    If it is routing permission, then slightly modify the above code and it can also be achieved by judging the session.
    If you use ui-router, you may consider adding this sentence to app.js:

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

    You may refer to another article for how to implement the specific Auth class:
    http://blog.coding.net/blog/techniques-for-authentication-in-angular-j...

    reply
    0
  • Cancelreply