简体   繁体   English

如何在路由前检查令牌有效性?

[英]How to check the token validity before routing?

I'm setting up a web application with angularjs routing (ngRoute) and expressjs in the backend. 我正在后端设置一个带有angularjs路由(ngRoute)和expressjs的Web应用程序。

I have a doubt, I don´t understand why the "standard" solution to check if user is logged or not is look up for the token in the local storage . 我有一个疑问, 我不明白为什么检查用户是否被记录的“标准”解决方案是在本地存储中查找令牌 I mean, its validity is not checked at any time . 我的意思是, 它的有效性不会随时检查 It is possible for the user to insert the token manually in the browser. 用户可以在浏览器中手动插入令牌。

I am aware that when the user tries to perform an operation the server side would realize that the user is not logged , but I think is still possible for a user who inserts manually the token to access some private routes (for example, a creation form). 我知道当用户尝试执行操作时,服务器端会意识到用户没有被记录 ,但我认为对于手动插入令牌以访问某些私有路由的用户来说仍然是可能的(例如,创建表单) )。

I don´t know how to resolve this problem. 我不知道如何解决这个问题。 I was trying to ask the server for the validity in the app run . 我试图在服务器运行中询问服务器的有效性 The problem is that the program does not wait for the promise before routing for the first time. 问题是程序在第一次路由之前不会等待承诺。

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);
          });
      }

  ...

Don't convert rejected promises 不要转换被拒绝的承诺

Why do so many examples on Stackoverflow convert rejected promises to fulfilled promises? 为什么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;
          });
      }

When a promise error handler returns a value, the $q service converts the rejected promise to a fulfilled promise. 当promise错误处理程序返回一个值时,$ q服务会将拒绝的 promise 转换为已履行的 promise。 To retain the rejected state, either re-throw a reason or return a rejected promise. 要保留被拒绝的状态,请重新抛出原因或返回被拒绝的承诺。

It looks like someone took a function named getProfile and hacked it to add side effects. 看起来有人拿了一个名为getProfile的函数并将其黑客攻击以添加副作用。 Instead of using the Profile promise, they discard the promise and use the side effects. 他们不使用Profile承诺,而是放弃承诺并使用副作用。

Return rejected promise to route resolve function 返回拒绝承诺路由解析功能

Functions that return rejected promises can be used in route resolve functions to abort loading a route: 返回被拒绝的promise的函数可以在路由解析函数中用于中止加载路由:

app.config(function($routeProvider, $locationProvider) {
    $routeProvider
    .when('/Book/:bookId', {
        templateUrl: 'book.html',
        controller: 'BookController',
        resolve: {
            profile: function(auth) {
                return auth.getProfile();
            }
        }
    })
})

When the auth.getProfile() function returns a rejected promise , the ngRoute router aborts the load of the view and broadcasts the $routeChangeError event. auth.getProfile()函数返回被拒绝的promise时 ,ngRoute路由器将中止视图的加载并广播$ routeChangeError事件。

For more information, see 有关更多信息,请参阅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM