曾经蜡笔没有小新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...