[英]MEAN Stack user authentication with passport-local and $routeProvider
我正在使用本地護照來將用戶登錄到我的應用程序。 我們通過以下在我的angularJS控制器中調用的函數登錄。
$http.post('/login', $scope.user).then(function (response){
if(response.data.success){
//If successful I console.log the user data and redirect them to the main page.
console.log(response.data.user);
$location.path(response.data.redirectTo);
} else {
// Handle the error messages passed back by my express routing.
}
});
這將按預期工作,如果我使用正確的詳細信息登錄,則它將console.log用戶,然后將我重定向到新頁面。
我的問題是我現在該如何做,以便我所有其他頁面都可以確保用戶已登錄? 我應該對接收到的用戶數據使用什么? 我正在談論的頁面使用以下$ routeProvider路由:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'login.html',
controller: 'loginCtrl'
});
$routeProvider.when('/home', {
templateUrl: 'home.html',
controller: 'homeCtrl',
// Something to make sure the user is logged in
});
}])
我閱讀的所有教程都要求我通過快速路由處理此問題,但這僅會導致重定向循環,因為/login
沒有通過isAuthenticated
路由中間件。
app.get('*', isAuthenticated, function(req,res){
res.sendFile("index.html");
});
function isAuthenticated(req,res,next){
if(req.isAuthenticated()){
next();
} else {
res.redirect('/login');
}
}
對於如何從這里前進的任何幫助將不勝感激。
您的angularJs應用需要檢測何時需要登錄。 為此,您需要為從Express應用程序獲得的所有響應編寫一個攔截器,如果需要登錄,請顯示登錄頁面。 在最好的情況下,您的快速應用程序不應重定向至/ login,而應將路由留給您的angularJs應用程序; 它將僅發送json資源或諸如401狀態代碼響應之類的內容來指示該請求未經授權。
收到未授權的標頭后,您的angularJs攔截器將看到需要登錄並顯示登錄頁面:
app.config(function($httpProvider) {
//configure $http to show a login dialog whenever a 401 unauthorized response arrives
$httpProvider.responseInterceptors.push(
function($rootScope, $q, $location) {
return function(promise) {
return promise.then(
//success -> don't intercept
function(response) {
return response;
},
//error -> if 401 save the request and broadcast an event
function(response) {
if (response.status === 403 || response.status === 401) {
var deferred = $q.defer(),
req = {
path: $location.path(),
config: response.config,
deferred: deferred
};
$rootScope.requests401.push(req);
$rootScope.$broadcast('event:loginRequired');
return deferred.promise;
}
return $q.reject(response);
}
);
};
});
});
app.run(function($rootScope, $http, $location, base64) {
/**
* Holds all the requests which failed due to 401 response.
*/
$rootScope.requests401 = [];
$rootScope.$on('event:loginRequired', function() {
$location.path('/login');
});
/**
* On 'event:loginConfirmed', resend all the 401 requests.
*/
$rootScope.$on('event:loginConfirmed', function(){
var i, requests = $rootScope.requests401,
retry = function(req) {
$http(req.config).then(function(response) {
req.deferred.resolve(response);
});
};
});
});
在此設置中,您的LoginCtrl還需要發出loginConfirmed事件。 一旦擁有登錄用戶,就可以將詳細信息存儲在根范圍中,以供以后訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.