[英]How to check the token validity before routing?
我正在后端設置一個帶有angularjs路由(ngRoute)和expressjs的Web應用程序。
我有一個疑問, 我不明白為什么檢查用戶是否被記錄的“標准”解決方案是在本地存儲中查找令牌 。 我的意思是, 它的有效性不會隨時檢查 。 用戶可以在瀏覽器中手動插入令牌。
我知道當用戶嘗試執行操作時,服務器端會意識到用戶沒有被記錄 ,但我認為對於手動插入令牌以訪問某些私有路由的用戶來說仍然是可能的(例如,創建表單) )。
我不知道如何解決這個問題。 我試圖在服務器運行中詢問服務器的有效性 。 問題是程序在第一次路由之前不會等待承諾。
var appRun = function($rootScope, $location, $route, $timeout, API_URL, auth, authToken) {
//running...
auth.getProfile();
$rootScope.$on('$locationChangeStart', function(event, next, current) {
var routeUrl = '/' + current.replace(API_URL, '').split('/')[1];
routeUrl = getRouteParams(routeUrl);
var routeObj = $route.routes[routeUrl];
var userProfile = authToken.isAuthenticated(), redirectPath;
//not valid route
if (!routeObj) {
redirectPath = getRedirectPath(userProfile);
$location.path(redirectPath);
}
//restricted route
else if (routeObj.restricted && userProfile !== 'LOGGED') {
redirectPath = getRedirectPath(userProfile);
$location.path(redirectPath);
}
...
}
}
//In auth service...
...
getProfile: function() {
if (!(!!authToken.getToken())) {
return authToken.setUserProfile('FORBIDDEN')
}
//if the token exists check it
return $http.get(API_URL + '/auth')
.then(function(response) {
authToken.setUserProfile(response.data.status);
return response;
})
.catch(function(error) {
return authToken.setUserProfile(error.data.message);
});
}
...
為什么Stackoverflow上的這么多例子會被拒絕承諾兌現承諾?
//In auth service...
...
getProfile: function() {
if (!(!!authToken.getToken())) {
̶ ̶r̶e̶t̶u̶r̶n̶ ̶a̶u̶t̶h̶T̶o̶k̶e̶n̶.̶s̶e̶t̶U̶s̶e̶r̶P̶r̶o̶f̶i̶l̶e̶(̶'̶F̶O̶R̶B̶I̶D̶D̶E̶N̶'̶)̶
authToken.setUserProfile('FORBIDDEN')
return $q.reject("FORBIDDEN - No token");
}
//if the token exists check it
return $http.get(API_URL + '/auth')
.then(function(response) {
authToken.setUserProfile(response.data.status);
return response;
})
.catch(function(error) {
̶r̶e̶t̶u̶r̶n̶ ̶a̶u̶t̶h̶T̶o̶k̶e̶n̶.̶s̶e̶t̶U̶s̶e̶r̶P̶r̶o̶f̶i̶l̶e̶(̶e̶r̶r̶o̶r̶.̶d̶a̶t̶a̶.̶m̶e̶s̶s̶a̶g̶e̶)̶;̶
authToken.setUserProfile(error.data.message);
//RE-THROW rejected promises
throw error;
});
}
當promise錯誤處理程序返回一個值時,$ q服務會將被拒絕的 promise 轉換為已履行的 promise。 要保留被拒絕的狀態,請重新拋出原因或返回被拒絕的承諾。
看起來有人拿了一個名為getProfile
的函數並將其黑客攻擊以添加副作用。 他們不使用Profile
承諾,而是放棄承諾並使用副作用。
返回被拒絕的promise的函數可以在路由解析函數中用於中止加載路由:
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookController',
resolve: {
profile: function(auth) {
return auth.getProfile();
}
}
})
})
當auth.getProfile()
函數返回被拒絕的promise時 ,ngRoute路由器將中止視圖的加載並廣播$ routeChangeError事件。
有關更多信息,請參閱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.