为特定用户在 stateProvider 上进行身份验证 (angular-fullstack)
Authenticate on stateProvider for a specific user (angular-fullstack)
我为我的项目使用 angular-fullstack 生成器 (https://github.com/angular-fullstack/generator-angular-fullstack),并且我的网站上有一个需求页面,需要由具有定义角色 (admin) 的用户访问。
此页面还需要可供创建需求的用户访问。
我知道我可以将 authenticate:true 放在我的状态提供者上以仅授权经过身份验证的用户,但我需要一个更精确的系统来满足我的情况,因为我需要只允许具有特定角色或特定角色的用户用户id.
有没有办法在 $state 重定向后在 stateProvider 中管理这种情况,或者我必须在我的页面控制器中执行此操作?
感谢您的宝贵时间
可以完成特定role
的授权,但需要修改一些代码。
将新字段 access
添加到您的 state
配置文件,如下所示。让我们将 authRequiredFor
数组存储在包含需要授权才能访问特定状态 myState
.
的角色中
angular.module('myApp')
.config(function ($stateProvider) {
$stateProvider
.state('myState', {
url: '...',
templateUrl: '...',
controller: '...',
access: {
authRequiredFor: ['role1', 'role2']
}
});
});
在你的app.js
文件中的run()
函数中,你需要添加和修改$stateChangeStart
回调函数以在访问任何状态之前检查用户是否需要身份验证。
.run(function ($rootScope, $location, Auth, $state) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$stateChangeStart', function (event, next) {
Auth.isLoggedInAsync(function(loggedIn) {
if (next.authenticate && !loggedIn) {
$location.url('/login');
}
if (next.access) { // check if the state config contains the field `access`
var permissions = next.access;
var userRole = Auth.getCurrentUser().role;
if (permissions.authRequiredFor) {
// check if the logged in user's role matches with the roles in the array
if (permissions.authRequiredFor.indexOf(userRole) >= 0) {
$location.url('/login'); // or redirect him to some other url/state
}
}
}
});
});
});
希望这能解决问题。
我为我的项目使用 angular-fullstack 生成器 (https://github.com/angular-fullstack/generator-angular-fullstack),并且我的网站上有一个需求页面,需要由具有定义角色 (admin) 的用户访问。 此页面还需要可供创建需求的用户访问。
我知道我可以将 authenticate:true 放在我的状态提供者上以仅授权经过身份验证的用户,但我需要一个更精确的系统来满足我的情况,因为我需要只允许具有特定角色或特定角色的用户用户id.
有没有办法在 $state 重定向后在 stateProvider 中管理这种情况,或者我必须在我的页面控制器中执行此操作?
感谢您的宝贵时间
可以完成特定role
的授权,但需要修改一些代码。
将新字段 access
添加到您的 state
配置文件,如下所示。让我们将 authRequiredFor
数组存储在包含需要授权才能访问特定状态 myState
.
angular.module('myApp')
.config(function ($stateProvider) {
$stateProvider
.state('myState', {
url: '...',
templateUrl: '...',
controller: '...',
access: {
authRequiredFor: ['role1', 'role2']
}
});
});
在你的app.js
文件中的run()
函数中,你需要添加和修改$stateChangeStart
回调函数以在访问任何状态之前检查用户是否需要身份验证。
.run(function ($rootScope, $location, Auth, $state) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$stateChangeStart', function (event, next) {
Auth.isLoggedInAsync(function(loggedIn) {
if (next.authenticate && !loggedIn) {
$location.url('/login');
}
if (next.access) { // check if the state config contains the field `access`
var permissions = next.access;
var userRole = Auth.getCurrentUser().role;
if (permissions.authRequiredFor) {
// check if the logged in user's role matches with the roles in the array
if (permissions.authRequiredFor.indexOf(userRole) >= 0) {
$location.url('/login'); // or redirect him to some other url/state
}
}
}
});
});
});
希望这能解决问题。