[英]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.