2013-06-20 9 views
9

Ho appena iniziato a lavorare con un'applicazione AngularJS che sto sviluppando, tutto sta andando bene, ma ho bisogno di un modo per proteggere i percorsi in modo che un utente non possa accedere a tale percorso se non ha effettuato l'accesso. l'importanza della protezione anche dal lato dei servizi e me ne occuperò io.AngularJS: proteggere i percorsi con angularjs a seconda che l'utente sia autorizzato?

ho trovato un certo numero di modi di proteggere il cliente, sembra di utilizzare il seguente

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

in cui ho bisogno di mettere questo, nel .run nel app.js?

E l'altro modo che ho trovato è usare una direttiva e utilizzando un on - routechagestart

informazioni è qui http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app

Vorrei davvero essere interessato anyones aiuto e feedback sul modo consigliato.

+1

http://www.egghead.io/ (gratuito) video 27-> 39 spiegare l'intera routing. Dovrebbe aiutarti. Il video più vicino è Resolve (35) – Utopik

+0

Grazie Utopik, Sì, ho già visto quelli. Penso di essere davvero alla ricerca di qualche input sul modo consigliato di fare quanto sopra. – Martin

risposta

16

Utilizzando risolve dovrebbe aiutare a qui: (codice non testato)

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

Grazie, quindi, se non autenticato, dovrei fare un $ location.path? per reindirizzare – Martin

+0

È possibile farlo tramite l'evento $ routeChangeError trasmesso sull'ambito del percorso quando una rotta non riesce. Aggiornerò la mia risposta –

+0

C'è un modo per farlo a livello globale per tutti i percorsi? – AndrewMcLagan

2

Un altro modo di utilizzare l'attributo resolve del $routeProvider:

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" 
    }); 

}]); 

In questo modo, se Access non risolve la promessa, l'evento $routeChangeError sarà licenziato:

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"); 
    } 
    }); 

}]); 

vedere il codice completo su this answer.

Problemi correlati