angularjs重定向到登录页面,如果不例外认证 [英] angularjs redirect to login page if not authenticated with exceptions

查看:842
本文介绍了angularjs重定向到登录页面,如果不例外认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:忘了提,我一直在与AngularJs只有一个星期,所以如果你看到,你觉得有什么应该变好了,并没有涉及到问题本身随时告诉我上的评论部分。

forgot to mention that i've been working with AngularJs for a week only, so if you see something you think should be changed for the better and is not related to the question itself feel free to tell me on the comments section.

好了,我有我的身份验证控制器和供应商,我将不会显示,因为他们是无关的问题的范围。
然后,我有一个拦截检查时,呼叫由用户进行身份验证。如果是这样我设置了验证头的请求,包括用户的令牌如果不是我将用户重定向到登录页面,甚至不发出请求到服务器(很明显,如果有人绕过这也是一个授权那里有关于API)。

ok, so I have my authentication Controllers and providers which I won't show because they're irrelevant for the scope of the question. Then I have an interceptor to check if the user is authenticated when a Call is made. If so I set the Authentication header on the request to include the user's Token if not I redirect the user to the login page and don't even make the request to the server (obviously if someone bypasses this theres also an Authorize on the API).

我要的是添加一些例外,这意味着有一些网页我想允许,即使用户没有身份验证令牌。我能够这样,如果它是一个特定的路径,但我想,以允许访问我的404页,它在路由是我指定。否则去404页,我该怎么做,这样我只拦截重定向到登录,如果它不会到这个页面。

What I want is to add a few exceptions, meaning there are some pages I want to allow even if the user has no Auth Token. I'm able to this if it's a specific path, but I want to allow my 404 page to be accessed and it's in the Routing that I'm specifying .otherwise to go to the 404 page, how can I make so that my interceptor only redirects to login if it's not going to this page.

拦截

.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;
}])

在我的路由

 $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

我尝试添加/页未找到我的如果,但它不会工作由时间,因为预期的位置被选中,第一次它仍然不是重定向。

I tried to add '/page-not-found' to my if but it won't work as expected because by the time the location is checked for the first time it's still not redirected.

修改
由于sugested由charlietfl我现在正在尝试使用决心,但它甚至没有通过我的功能。

edit As sugested by charlietfl I'm now trying to use resolve but it's not even passing my function.

我删除了这个code从我的拦截器:

I removed this code from my interceptor:

else if ($location.path != '/accounts/login' && $location.path != '/accounts/register') {
    $location.path('/accounts/login');
}

和添加一个新的服务来验证模块:

and add a new service to the authentication module:

.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;
}]);

和我试图称呼其为:

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

注意到,我试图登录的authData VAR 来检查,如果它的工作,但它是不是这里面的控制台也没有错误。

notice that i'm trying to log authData var to check if it's working but it isn't and there's no error on the console also.

推荐答案

终于想通了如何使用决心解决这个问题。

Finally figured out how to solve it using resolve.

首先我完全删除我之前使用的拦截器。
然后我做了一个功能我的路由的.config 里面的每决心的身份验证使用。终于来处理我的决心我用 $ stateChangeError 来重定向到登录状态

first of all I completely removed the interceptor I was using before. then I made a function inside my Routing .config to use with every resolve for the authentication. finally to handle my resolve I'm using $stateChangeError to redirect to the login 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 //
    }
);

在MainController

in the MainController

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

这篇关于angularjs重定向到登录页面,如果不例外认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆