如何限制对经过身份验证的用户的访问?

时间:2016-11-02 14:41:02

标签: angularjs authentication

我将Angularjs中的以下控制器/服务放在一起以联系身份验证服务。我想利用它将Angular应用程序的其他页面限制为通过此服务进行身份验证的用户,但我不知道该怎么做。我希望有人能指出我正确的方向。以下是我的控制器和服务。

angular.module('App').controller('LoginController', function ($scope, $rootScope, $window, AuthenticationService) {

//function that gets called when the form is submitted. 
$scope.submit = function () {
    var promise = AuthenticationService.login($scope.user, $scope.password);

    promise.then(function () {
        var success = AuthenticationService.isAuthenticated();
        if (success === true) {
            $window.location.href = "/welcome.html";
        }
    });
} 
});

app.service('AuthenticationService', function ($http) {
//Used to track if the user was able to successfully authenticate. 
var auth = false;
var token = undefined; 

//Had to put this in because I am running into weird behavior when attempting to retrieve a value from response.headers('value');.
//When assiging this to a var, it would always come out as a null value. If you send the value into a function without assigning 
//it to a var, the value would be there as expected. For instance, console.log(response.headers('Authorization')); would work, but
//token = response.headers('A‌​uthorization'); would result in a null value. The function below is a workaround. 
var getResponseHeader = function (x) { return x; }

//Makes a call to the WEB API Authentication service with the username/password and attempts to authenticate. 
var login = function (user, pass) {
    var input = { UserName: user, Password: pass };

    return $http({
        url: "/api/Authentication/Login/{credentials}",
        method: "POST",
        data: JSON.stringify(input),
        dataType: "json"
    }).then(function (response) {
        if (response.status === 200) { //Call to the service was successful.

            //This makes no sense. See comment for getResponseHeader function. 
            token = getResponseHeader(response.headers('Authorization'));

            //If the authentication was successful, 'token' will have a value. If it was not successful, it will be null. 
            if (token) {
                auth = true; 
            }
        }
        //There was an error when attempting to authenticate. Alert(response) is there for debugging purposes. 
        //This will be replaced with a user-friendly error message when completed.
    }, function (response) { 
        alert(response); 
    });
}

//Logs the user out by removing the token and setting auth back to false
var logout = function (sessionid) {
    auth = false;
    token = undefined; 
}

//Accessor for the 'auth' variable.
var isAuthenticated = function () { return auth; }

//Accessor for the token. 
var getToken = function () { return token; } 

return {
    login: login,
    logout: logout,
    isAuthenticated: isAuthenticated,
    token: getToken
}; 
});

服务/控制器可以进行身份​​验证,但是任何人都可以浏览到“welcome.html'或应用程序中的任何其他页面。如何将此限制为已成功通过身份验证的用户?

2 个答案:

答案 0 :(得分:0)

我建议使用angular-permissions

你设置你的状态如下:

.state('home', {
        url: '/',
        templateUrl: 'templates/home.html',
        parent: 'parent',
        data: {
          permissions: { //section for permissions
            only: 'isAuthorized',  // only allow loged in users
            redirectTo: 'login'    // if not allowed redirect to login page
          }
        },
      })

.state('login', {
        url: '/login',
        templateUrl: 'templates/login.html',
        parent: 'login-parent',
        data: {
          permissions: {
            only: 'anonymous',
            redirectTo: 'home'
          }
        }
      })

并设置两组进行身份验证:

//A Group for not logged in users
.run(function(PermPermissionStore) {
  PermPermissionStore
    .definePermission('anonymous', function() {
      // Do your authentification here
      // you can sett up your funtions elsewere and call them here
      // return true if unauthorized
      var auth = auth_function()
      if (auth === true) {
         return false
      } else { return true }
    })
})

//group for authentificated users
.run(function(PermPermissionStore) {
PermPermissionStore
  .definePermission('isAuthorized', function() {
      // Do your authentification here
      // return true if authorized
      var auth = auth_function()
      if (auth === true) {
         return true
      } else { return false }
  })
})

答案 1 :(得分:0)

在您的根应用程序js文件运行方法检查auth值并重定向如果未经过身份验证,app.js上的run方法是设置此监视的好地方:

SEE FIDDLE EXAMPLE OF YOUR CODE

.run(['AuthenticationService', '$location', '$rootScope', function (AuthenticationService, $location, $rootScope) {

            $rootScope.$watch(function () {
                if (!AuthenticationService.isAuthenticated())
                    $location.path("/login");

                return $location.path();
            });


        }])

这个简单的监视器将通过在AuthenticationService中调用isAuthenticated方法来检查auth值,因此您可以确定没有未经过处理的用户将访问任何页面,您应该通过添加另一个条件来更改逻辑以检查路由以便仅限制访问指定的页面。