歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> AngularJS如何做身份驗證

AngularJS如何做身份驗證

日期:2017/3/1 9:44:04   编辑:Linux編程

如果要在客戶端使用AngularJS做身份驗證的話,推薦使用service來做,因為service是單例的,可以很方便的在所有view,controller,directives,filters和其他service中共享數據,而不用采取暴露全局變量的方式,封裝性也有一定的保障。

帶你走近AngularJS系列

  1. 帶你走近AngularJS - 基本功能介紹 http://www.linuxidc.com/Linux/2014-05/102140.htm
  2. 帶你走近AngularJS - 體驗指令實例 http://www.linuxidc.com/Linux/2014-05/102141.htm
  3. 帶你走近AngularJS - 創建自定義指令 http://www.linuxidc.com/Linux/2014-05/102142.htm

如何在 AngularJS 中對控制器進行單元測試 http://www.linuxidc.com/Linux/2013-12/94166.htm

AngularJS 之 Factory vs Service vs Provider http://www.linuxidc.com/Linux/2014-05/101475.htm

一個簡單的例子:

services.factory('UserService', [function() {
var sdo = {
isLogged: false,
username: ''
};
return sdo;
}]);

AngularJS中使用service都是通過依賴聲明的方式來做的,比如:

var controllers = angular.module('myApp.controllers', []);

/* ... */

controllers.controller('loginController', ['$scope', '$http', 'UserService', function(scope, $http, User) {

}]);

在這個loginController裡我們可以定義一個login function來向服務器驗證用戶身份:

scope.login = function() {
var config = { /* ... */ } // configuration object

$http(config)
.success(function(data, status, headers, config) {
if (data.status) {
// succefull login
User.isLogged = true;
User.username = data.username;
}
else {
User.isLogged = false;
User.username = '';
}
})
.error(function(data, status, headers, config) {
User.isLogged = false;
User.username = '';
});
}

接著,只要聲明依賴了UserService的任何controller,view,filter等都可以通過UserService.isLogged來判斷用戶是否是已經驗證過的,或者匿名用戶


由於AngularJS通常會使用template把頁面拆分重組,此時使用routeProvider來控制各個頁面的訪問規則:

app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', { templateUrl: 'partials/login.html', controller: 'loginCtrl' , access: {isFree: true}});
$routeProvider.when('/main', { templateUrl: 'partials/main.html', controller: 'mainCtrl' });
$routeProvider.otherwise({ redirectTo: '/main' });
}]);

有的頁面是無需身份驗證就可以訪問的,例如login.html,有的頁面是需要登錄用戶才能夠看到的,例如main.html,此時我們就需要通過增加通用的checkUser邏輯來判斷當前用戶是否能看到這些頁面:

directives.directive('checkUser', ['$rootScope', '$location', 'userSrv', function ($root, $location, userSrv) {
return {
link: function (scope, elem, attrs, ctrl) {
$root.$on('$routeChangeStart', function(event, currRoute, prevRoute){
if (!prevRoute.access.isFree && !userSrv.isLogged) {
// reload the login route
}
/*
* IMPORTANT:
* It's not difficult to fool the previous control,
* so it's really IMPORTANT to repeat the control also in the backend,
* before sending back from the server reserved information.
*/
});
}
}
}]);

這個directive注冊在了rootScope上,並且監聽了routeChangeStart,也是一種AOP的概念,在route change發生之前,織入了一個切面,來判斷用戶身份權限。由此,來達到在AngularJS中驗證身份的整個邏輯。

AngularJS 的詳細介紹:請點這裡
AngularJS 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved