我创建了一个 github 存储库,基本上总结了这篇文章:https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
ng-login Github repo
Plunker
我会尽量解释清楚,希望对你们中的一些人有所帮助:
(1) app.js:在应用定义中创建身份验证常量
var loginApp = angular.module('loginApp', ['ui.router', 'ui.bootstrap'])
/*Constants regarding user login defined here*/
.constant('USER_ROLES', {
all : '*',
admin : 'admin',
editor : 'editor',
guest : 'guest'
}).constant('AUTH_EVENTS', {
loginSuccess : 'auth-login-success',
loginFailed : 'auth-login-failed',
logoutSuccess : 'auth-logout-success',
sessionTimeout : 'auth-session-timeout',
notAuthenticated : 'auth-not-authenticated',
notAuthorized : 'auth-not-authorized'
})
(2) Auth Service: 以下所有功能均在 auth.js 服务中实现。 $http 服务用于与服务器通信以进行身份验证过程。还包含授权功能,即是否允许用户执行特定操作。
angular.module('loginApp')
.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS',
function($http, $rootScope, $window, Session, AUTH_EVENTS) {
authService.login() = [...]
authService.isAuthenticated() = [...]
authService.isAuthorized() = [...]
authService.logout() = [...]
return authService;
} ]);
(3) 会话: 保存用户数据的单例。这里的实现取决于你。
angular.module('loginApp').service('Session', function($rootScope, USER_ROLES) {
this.create = function(user) {
this.user = user;
this.userRole = user.userRole;
};
this.destroy = function() {
this.user = null;
this.userRole = null;
};
return this;
});
(4) 父控制器: 将其视为应用程序的“主要”功能,所有控制器都继承自此控制器,它是此应用程序身份验证的支柱。
<body ng-controller="ParentController">
[...]
</body>
(5) 访问控制:要拒绝某些路线的访问,必须执行 2 个步骤:
a) 在 ui 路由器的 $stateProvider 服务上添加允许访问每个路由的角色数据,如下所示(同样适用于 ngRoute)。
.config(function ($stateProvider, USER_ROLES) {
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard/index.html',
data: {
authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]
}
});
})
b) 在 $rootScope.$on('$stateChangeStart') 上添加功能以防止用户未授权时更改状态。
$rootScope.$on('$stateChangeStart', function (event, next) {
var authorizedRoles = next.data.authorizedRoles;
if (!Auth.isAuthorized(authorizedRoles)) {
event.preventDefault();
if (Auth.isAuthenticated()) {
// user is not allowed
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
} else {
// user is not logged in
$rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
}
}
});
(6) Auth拦截器:这个是实现的,但是不能对这段代码的范围进行检查。在每个 $http 请求之后,此拦截器都会检查状态码,如果返回以下之一,则它会广播一个事件以强制用户重新登录。
angular.module('loginApp')
.factory('AuthInterceptor', [ '$rootScope', '$q', 'Session', 'AUTH_EVENTS',
function($rootScope, $q, Session, AUTH_EVENTS) {
return {
responseError : function(response) {
$rootScope.$broadcast({
401 : AUTH_EVENTS.notAuthenticated,
403 : AUTH_EVENTS.notAuthorized,
419 : AUTH_EVENTS.sessionTimeout,
440 : AUTH_EVENTS.sessionTimeout
}[response.status], response);
return $q.reject(response);
}
};
} ]);
P.S. 通过添加包含在directives.js 中的指令,可以轻松避免第一篇文章中所述的表单数据自动填充错误。
P.S.2 用户可以轻松调整此代码,以允许看到不同的路线,或显示不应该显示的内容。逻辑必须在服务器端实现,这只是在您的 ng-app 上正确显示内容的一种方式。