User permission - Angularjs

Asked

Viewed 995 times

3

I have permission levels for users on my system: admin user and basic user.

I have a page that only administrator users can access. I put an ng-if="isAdmin()" in the menu to hide, if not administrator.

It works correctly, but if by chance the user tries to access the page through the browser URL, he is able to access the page. As I do in Angularjs, do not let access this page if the user is not administrator type?

I’m using ui-router and the Angular version is 1.6 :)

This is my code:

//Rotas
app.config(function($routeProvider) {
$routeProvider.when('/', {
    templateUrl : 'home.html',
})

$routeProvider.when('/appointments', {
    templateUrl : 'views/appointment/appointment.html',
    controller : 'AppointmentController'
})

$routeProvider.when('/patients', {
    templateUrl : 'views/patient/patient.html',
    controller : 'PatientController'
})

$routeProvider.when('/users', {
    templateUrl : 'views/user/user.html',
    controller : 'UserController',

})

$routeProvider.when('/services', {
    templateUrl : 'views/service/service.html',
    controller : 'ServiceController'
})
});

 /* Load para pegar as informações do usuário logado */
$scope.getUserData = function(){
    OdontoService.load('rest/user/getUserData').then(function (data) { 
        $scope.userAuthenticated = data.data;
        localStorage.setItem('permission', $scope.userAuthenticated.permission);
        $scope.isLoading = false;
    },function (error){
        console.log(error);
    });
}

$scope.isAdminUser = function(){
    return localStorage.getItem('permission') == 0;
}

Permission 0 means user is administrator.

  • Post all the code

  • You have to put the isAdmin() function to be executed on an initiator, so every time you execute a request, the intercep checks whether it is permissible or not. Put code that we help more.

  • @Virgilionovic I changed the question, with the code of my project.

  • @Marcossouza I changed the question, with the code of my project.

4 answers

5

Do not use angular to deny access to pages. The user can modify the Javascript loaded in the browser, even if it is obfuscated (i.e.: minified) and access the page anyway.

The only secure way to authorize access is on the server, with its preferred technology (PHP, Java, . NET, Javascript on Node.js etc.)

0

It is important that your back-end has a security module with permissions to enhance the security of your application. With the angular, using the ui-router, vc can reinforce in the "state" configuration of the page to be called. See below:

.state('home', {
    url: '/home',
    templateUrl: 'home.html',
    controller: 'HomeController',
    resolve: {
        deps: function($q, $state) {

            var deferred = $q.defer();
            // Aqui verifica se o usuário é do tipo Administrador, caso sim, o state será resolvido e a página será carregada
            if(isAdmin())
                deferred.resolve();
            else{
                // Caso não, redireciona para a tela de login
                $state.go('login', { reload: true });
                deferred.reject()
            }

            return deferred.promise;
        }
    }
})

I hope I’ve helped.

  • 1

    I still believe that handling security matters via angular is similar to doing something like this: http://rubmint.com/wp-content/plugins/wp-o-matic/cache/74842_epic-fail-turnstile-fail.jpg

0

As you are using the ui-router this check can be done every time the state is changed($state) you can add in the route if you need to login or not, or if you need to be admin to access some View resource; You can recover the value in the controller, but then you will need to use $state.current.data

(function () {
    'use strict';

    angular
        .module('app')
        .run(configRun)
    function configRun($rootScope, $state) {


        $rootScope.$on('$stateChangeStart', function (evt, to, toParams, from, fromParams) {


            if (to.data && to.data.requiresLogin && !$rootScope.user) {
                evt.preventDefault();
                $state.go('home');
            }

            if (toParams.codigo) {
                userService.getUserData()
                    .then(function (data) {
                        $rootScope.user = data;
                    });
            }

        });
    }
})();


(function () {
    'use strict';
    angular.module('app')

        .config(configRouter);
    /** @ngInject */
    function configRouter($stateProvider, $urlRouterProvider, $httpProvider, $ionicConfigProvider) {


        $ionicConfigProvider.views.maxCache(0);
        $httpProvider.interceptors.push('TokenInterceptor');
        $stateProvider

            .state('home', {
                url: "/",
                templateUrl: 'home/home.html',
                controller: 'HomeController',
                controllerAs: 'home',
            })
            .state('panic', {
                url: "/panic/:codigo",
                templateUrl: 'security/panic/panic.html',
                controller: 'PanicController',
                controllerAs: 'panic',
                params: {dataModal: null},

                data: {requiresLogin: true},
            })

            .state('login', {
                url: "/login",
                templateUrl: 'login/login.html',
                controller: 'LoginController',
                controllerAs: 'login',
                data: {teste: true},
            })

            .state('app', {
                url: "/app/:codigo",
                abstract: true,
                views: {

                    '': {
                        templateUrl: 'layout/layout.html',
                        controller: 'AppController'
                    },

                    'sidenav': {
                        templateUrl: 'layout/sidenav/sidenav.html',
                        controller: 'sidenavController',
                        controllerAs: 'sidenav',
                    },
                    'content': {
                        templateUrl: 'layout/content.html'
                    },
                    'footer': {
                        templateUrl: 'layout/footer/footer.html',
                        controller: 'footerController',
                        controllerAs: 'ft'

                    },
                    'security': {
                        templateUrl: 'security/security.html',
                        controller: 'SecurityController',
                        controllerAs: 'security'

                    },
                    'aside': {
                        templateUrl: 'layout/toolbar/toolbar.html',
                        controller: 'toolbarController',
                        controllerAs: 'toolbar',
                    },

                },

                data: {requiresLogin: true}

            })
        
        // if none of the above states are matched, use this as the fallback
        $urlRouterProvider.otherwise('/');
        $urlRouterProvider.when('', '/home');


    }

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  • This is great if users are limited to the elderly family, but when this falls into the hands of a nephew of yours who knows how to use the browser console it is no longer safe.

  • @Renan has something that has to be dealt with in the back end, has something that has to be dealt with in the front end and has something that has to be dealt with both in the front end and in the back end. At no time have I told him not to treat the business rules in Backend; but there is something that the front end has to deal with,

0

Create a third party to execute the admin function whenever there is a request. It could be like this:

//interceptador
angular.module('seuapp').factory('authInterceptor', function($rootScope, $q){
  return{
    //O que colocar aqui será executado na requisição
    //Se fosse setar alguma coisa no header seria feito  no request.
    request: function(){
    //Verifica se tem permissão antes de envia-la
      if(localStorage.getItem('permission') != 0){
        //Se não tiver redireciona para login
        location.assign('/login')
      }
      return console.log("Acesso verificado.");
    },

    response: function(response){
      //Aqui você pode por alguma coisa que seja feita caso a pagina ou api 
      //que você esteja trabalhando retorne alguma coisa, tipo um token etc.
  }
});

//Depois você deve registrar o interceptor na sua aplicação.
angular.module('seuapp').config(function($httpProvider){
  //Aqui faz com que em toda as requições http seja executado o request/response.
  $httpProvider.interceptors.push('authInterceptor');
});

Just a background check, that kind of authentication is zero level. I created an application that gives to have a notion about other means of authenticity.da a look can help. https://github.com/marcossouzadev/booklist

Browser other questions tagged

You are not signed in. Login or sign up in order to post.