如果未通过异常进行身份验证,angularjs将重定向到登录页面

Fab*_*ioG 2 authentication redirect routing angularjs

编辑:忘了提到我已经和AngularJs一起工作了一个星期,所以如果你看到一些你认为应该改善的东西并且与问题无关,请随时在评论部分告诉我.


好的,所以我有我的身份验证控制器和提供程序,我不会显示,因为它们与问题的范围无关.然后我有一个拦截器来检查用户是否在进行呼叫时进行了身份验证.如果是这样的话,我Authentication在请求上设置标题以包括用户的令牌,如果不是我将用户重定向到登录页面,甚至不向服务器发出请求(显然如果有人绕过它,那么也是AuthorizeAPI上的).

我想要的是添加一些例外,这意味着即使用户没有Auth Token也有一些我想要允许的页面.如果它是一个特定的路径,我能够这样做,但是我想允许访问我的404页面并且它Routing是我指定.otherwise去404页面的,我怎样才能使我的拦截器只重定向到登录,如果它不会到这个页面.

拦截器

.factory('authInterceptorService', ['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {

    var authInterceptorServiceFactory = {};

    var authData = localStorageService.get('authorizationData');

    var _request = function (config) {

        config.headers = config.headers || {};

        if (authData) {
            config.headers.Authorization = 'Bearer ' + authData.token;
        } else if ($location.path != '/accounts/login' && $location.path != '/accounts/register') {
            $location.path('/accounts/login');
        }

        return config;
    }

    var _responseError = function (rejection) {
        if (rejection.status === 401) {
            $location.path('/accounts/login');
        }
        return $q.reject(rejection);
    }

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;

    return authInterceptorServiceFactory;
}])
Run Code Online (Sandbox Code Playgroud)

在我的路由

 $urlRouterProvider.otherwise('/page-not-found');

 $stateProvider
     (...)//rest of the states

     .state('page-not-found', {
         url: '/page-not-found',
         templateUrl: '/Content/partials/error/404.html',
         data: {
             displayName: false
         }
     })

     (...)//rest of the states
Run Code Online (Sandbox Code Playgroud)

我试图添加'/page-not-found'到我的,if但它不会按预期工作,因为当第一次检查位置时,它仍然没有被重定向.

编辑 由于charlietfl的消化现在我正在尝试使用解决方案,但它甚至没有通过我的功能.

我从拦截器中删除了这段代码:

else if ($location.path != '/accounts/login' && $location.path != '/accounts/register') {
    $location.path('/accounts/login');
}
Run Code Online (Sandbox Code Playgroud)

service在身份验证模块中添加新内容:

.service('authCheckService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
    var self = {
        'onlyLoggedIn': function ($state, $q) {
            var deferred = $q.defer();
            var authData = localStorageService.get('authorizationData');
            console.log(authData);
            if (authData) {
                deferred.resolve();
            } else {
                deferred.reject();
                $state.go('login');
            }
            return deferred.promise;
        }
    }

    return self;
}]);
Run Code Online (Sandbox Code Playgroud)

我试着把它称为:

.state('smo-dashboard', {
        url: '/dashboard',
        templateUrl: '/Content/partials/dashboard.html',
        resolve: authCheckServiceProvider.onlyLoggedIn
})
Run Code Online (Sandbox Code Playgroud)

请注意,我正在尝试记录authData var以检查它是否正常工作但它不是并且控制台上也没有错误.

Fab*_*ioG 6

最后想出了如何使用resolve解决它.

首先,我完全删除了之前使用过的拦截器.然后我在我的路由中创建了一个函数.config,用于每个resolve身份验证.终于处理我resolve正在使用$stateChangeError的重定向到登录state

路由配置

.config(function ($stateProvider, $urlRouterProvider) {

    // function to check the authentication //
    var Auth = ["$q", "authService", function ($q, authService) {
        authService.fillAuthData;
        if (authService.authentication.isAuth) {
            return $q.when(authService.authentication);
        } else {
            return $q.reject({ authenticated: false });
        }
    }];

    /* if the state does not exist */
    $urlRouterProvider
        .otherwise('/page-not-found'); 

    $stateProvider

        // state that allows non authenticated users //
        .state('home', {
            url: '/',
            templateUrl: '/Content/partials/home.html',
        })

        // state that needs authentication //
        .state('smo-dashboard', {
            url: '/dashboard',
            templateUrl: '/Content/partials/dashboard.html',
            resolve: {
                auth: Auth
            }
        })

        // errors //
         .state('page-not-found', {
             url: '/page-not-found',
             templateUrl: '/Content/partials/error/404.html'
         })

        // accounts //
        .state('login', {
            url: '/accounts/login',
            templateUrl: '/Content/partials/account/login.html'
        })

        // OTHER STATES //
    }
);
Run Code Online (Sandbox Code Playgroud)

在MainController中

$scope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
    $state.go("login");
});
Run Code Online (Sandbox Code Playgroud)