2013-06-20 1 views
9

방금 ​​AngularJS 앱을 개발하기 시작했습니다. 모든 것이 잘 진행되고 있지만 로그인하지 않은 경우 사용자가 해당 경로로 이동할 수 없도록 경로를 보호해야합니다. 서비스 측면에서 보호의 중요성 또한 내가 돌볼 것입니다.AngularJS : 사용자가 권한이 있는지에 따라 angularjs가있는 경로를 보호 하시겠습니까?

나는 클라이언트를 보호하는 여러 가지 방법을 발견했다

, 하나는 사용하는 것 같다하여 app.js에서 .run에서 내가 이것을 넣어해야합니까

$scope.$watch(
    function() { 
     return $location.path(); 
    }, 
    function(newValue, oldValue) { 
     if ($scope.loggedIn == false && newValue != '/login') { 
      $location.path('/login'); 
     } 
    } 
); 

을, 다음?

그리고 나는 지시어를 사용하고에 사용 발견 다른 방법 - routechagestart

정보] 여기 http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app

정말 권장되는 방법에 anyones에 도움과 피드백에 관심이있을 것입니다. Access가 해결되지 않을 경우,

angular.config(["$routeProvider", 
function($routeProvider) { 

    "use strict"; 

    $routeProvider 

    .when("/forbidden", { 
    /* ... */ 
    }) 

    .when("/signin", { 
    /* ... */ 
    resolve: { 
     access: ["Access", function(Access) { return Access.isAnonymous(); }], 
    } 
    }) 

    .when("/home", { 
    /* ... */ 
    resolve: { 
     access: ["Access", function(Access) { return Access.isAuthenticated(); }], 
    } 
    }) 

    .when("/admin", { 
    /* ... */ 
    resolve: { 
     access: ["Access", function(Access) { return Access.hasRole("ADMIN"); }], 
    } 
    }) 

    .otherwise({ 
    redirectTo: "/home" 
    }); 

}]); 

이 방법 :

+1

http://www.egghead.io/ (무료) 비디오 27-> 39는 전체 라우팅 정보를 설명합니다. 도움이 될 것입니다. 가장 가까운 비디오는 Resolve (35) – Utopik

+0

입니다. Thanks Utopik, 그렇습니다. 나는 이미 그것을 보았습니다. 위의 작업을 수행하는 데 권장되는 방법에 대한 정보를 찾고 있다고 생각합니다. – Martin

답변

16

결의를 사용하여 여기에 당신을 도울해야 다음 $routeProviderresolve 속성을 사용

angular.module('app' []).config(function($routeProvider){ 
    $routeProvider 
     .when('/needsauthorisation', { 
      //config for controller and template 
      resolve : { 
       //This function is injected with the AuthService where you'll put your authentication logic 
       'auth' : function(AuthService){ 
        return AuthService.authenticate(); 
       } 
      } 
     }); 
}).run(function($rootScope, $location){ 
    //If the route change failed due to authentication error, redirect them out 
    $rootScope.$on('$routeChangeError', function(event, current, previous, rejection){ 
     if(rejection === 'Not Authenticated'){ 
      $location.path('/'); 
     } 
    }) 
}).factory('AuthService', function($q){ 
    return { 
     authenticate : function(){ 
      //Authentication logic here 
      if(isAuthenticated){ 
       //If authenticated, return anything you want, probably a user object 
       return true; 
      } else { 
       //Else send a rejection 
       return $q.reject('Not Authenticated'); 
      } 
     } 
    } 
}); 
+0

$ location.path는 어디에서 인증을해야합니까? 리디렉션 할 – Martin

+0

경로가 실패 할 때 경로 범위에 대해 브로드 캐스팅 된 $ routeChangeError 이벤트를 통해이 작업을 수행 할 수 있습니다. 내 대답을 업데이트 할게 –

+0

모든 경로에서이 작업을 전체적으로 수행 할 수있는 방법이 있습니까? – AndrewMcLagan

2

또 다른 방법 (코드는 테스트하지) 약속, 이벤트가 발생합니다 :

angular.run(["$rootScope", "Access", "$location", 
function($rootScope, Access, $location) { 

    "use strict"; 

    $rootScope.$on("$routeChangeError", function(event, current, previous, rejection) { 
    if (rejection == Access.UNAUTHORIZED) { 
     $location.path("/login"); 
    } else if (rejection == Access.FORBIDDEN) { 
     $location.path("/forbidden"); 
    } 
    }); 

}]); 

this answer에 전체 코드를 참조하십시오.

관련 문제