我还没有找到任何关于此问题的内容,请原谅我,如果已经以其他形式提出这个问题。
我使用Angular-UI-Router作为我的首选路由方法,使用Ruby on Rails 4作为我的后端API。我正在构建一个基于用户的应用程序(因为将有数百/数千个用户)。每个用户都有自己的帐户来存放他们的信息,并且可以进行编辑。每个用户已经拥有一个authentication_token,当他们登录时,他们会在服务器端生成,存储在数据库中,然后在登录时将客户端存储为临时cookie。
我为帐户授权所做的是定义状态是否需要在状态解析期间进行授权检查,然后如果确实如此,我检查用户的状态ID参数是否与其用户ID(设置为cookie)匹配以及是否authentication_token(cookie)与API中定义的authorization_token相同。代码如下。我正在使用Restangular模块来发出HTTP请求,这个代码在应用程序的顶级“运行”周期中使用(它是一个init文件)。
我想知道这是否是一个有效的解决方案,潜在的缺点或安全漏洞可能是什么,如果这是一个坏主意,什么是AngularJS中基于帐户的授权更有效的解决方案?
提前致谢!
$rootScope.$on('$stateChangeStart', function (event, next, toState) {
// Restrict access if authorization is required from state data ("authRequired" is defined in module config files as part of the state definitions)
if (next.data.authRequired) {
Auth.getCurrentUser().then(function(user) {
// Validate the user's token by checking if the "auth_token" cookie matches the user's API auth_token
var user_token = user.auth_token;
var auth_token = $cookieStore.get('auth_token');
var validateAuthToken = (function() {
return (auth_token === user_token) ? true : false;
})();
// Validate the user's ID by checking if the "uid" cookie matches the ID of the state param that is being requested.
var uid = $cookieStore.get('uid');
var sid = parseInt(toState.id);
var validateUserID = (function() {
return (uid === sid) ? true : false;
})();
// If either validation is false, restrict access
if (validateAuthToken && validateUserID === false) {
event.preventDefault();
if (Auth.isLoggedIn() === true) {
// user is not allowed
$state.go('home');
alertService.showAlert(AUTH_EVENTS.notAuthorized, 'alert-danger');
} else {
// user is not logged in
$state.go('auth.login');
alertService.showAlert(AUTH_EVENTS.notAuthenticated, 'alert-danger');
}
}
});
}