我尝试根据身份验证重定向用户,因此在每个路由状态的解析中,我已经放置了我的服务来检查身份验证,所以在这种情况下登录和仪表板。
.state('login', {
url: "/login",
abstract: true,
templateUrl: '/app/login/login.html'
})
// Default login state
.state('login.index', {
url: "",
templateUrl: "/app/login/views/login.html",
controller: 'LoginController',
controllerAs: 'loginCtrl',
resolve: {
UserAuth: session
}
})
.state('dashboard', {
url: "/dashboard",
abstract: true,
templateUrl: '/app/dashboard/dashboard.html',
resolve: {
UserAuth: session
}
})
// Default dashboard state
.state('dashboard.index', {
url: "",
templateUrl: '/app/dashboard/views/page1.html',
controller: 'Page1Controller',
controllerAs: 'page1Ctrl',
resolve: {
UserAuth: session
}
})
// with multiple states like the child route above...
在我的路由配置中,我还设置了上面使用的会话,在会话中成功或存在会话$ state.go到仪表板,否则在promise失败$ state.go登录。
.config(function($stateProvider, $urlRouterProvider) {
var session = ['$q', '$location', '$state', 'SessionService',
function( $q, $location, $state, SessionService ) {
return SessionService.session()
.then(function( session ) {
// Check location path as $state is not resolved yet
var location = $location.path();
/**
* Check user authentication to dashboard and handle
* state change if session already exists
*/
if( location.indexOf('login') === 1 ) {
// Redirect to default dashboard view
$state.go('dashboard.index');
}
}, function( error ) {
// Check location path as $state is not resolved yet
var location = $location.path();
/**
* Check for unauthorized access to dashboard and handle
* state change if not located on login view
*/
if( location.indexOf( 'dashboard' ) === 1 ) {
// Redirect to default login view
$state.go('login.index');
}
// Don't propagate error since it has been handled and it prevents page
// return $q.reject( error );
});
}];
但是,当我让会话超时时,它会遇到无限循环的403错误,这是承诺失败的正确服务器响应。它进入if语句,并运行$ state.go(' login.index'),但保持循环并且永远不会用login替换状态。谁能看到我做错了什么?除了会话超时以外的所有情况都适用,然后不会重定向。
答案 0 :(得分:2)
我把我在过去的项目中使用的一些代码放在一起,这个代码显示了我如何在Angular方面设置身份验证和拦截401/403。
https://gist.github.com/jfornoff/4637069c398dc2f5b881
请注意,特别是用户的授权无法在前端可靠地进行,并且始终让您的后端进行身份验证,而不是盲目地将数据提供给您的前端应该使用的某些终点;-)但我猜这&#39 ; s非常明显。
希望我能帮到你! 再见, 扬