4

我在节点应用程序中放置了一个 JWT 身份验证系统。

我使用拦截器将 Bearer 放入每个请求中。如果我在 Angular 中调用受限路由,或者如果我 curl 并在标头中指定令牌,它会很好地工作。
但是如果我直接在我的地址栏中输入受限路线,它就不起作用了。标头中没有 Bearer,它不通过拦截器。

这是我的拦截器(客户端):

angular.module('myApp).factory('authInterceptor', function ($rootScope, $q, $window) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.localStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
      }
      return config;
    },
    responseError: function (rejection) {
      if (rejection.status === 401) {
        // handle the case where the user is not authenticated
      }
      return $q.reject(rejection);
    }
  };
});
angular.module('myApp').config(function ($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
});

这是我的受限路线(服务器端):

router.get('/restricted', expressJwt({secret: 'SecretStory'}), function(req, res) {
  res.json({
      name: 'You are allowed here !!'
    });
})

如何在每个请求中将承载添加到我的请求标头中,即使直接在地址栏中输入受限路由?

4

1 回答 1

2

当您直接在地址栏中输入 URL 时,您正在绕过您的 Angular 代码,并且正如您所发现的,拦截器将不会运行。

可以尝试检测地址栏中的 URL 何时更改并尝试解决该问题,但我建议您不要这样做。

相反,我会通过检测带有(任何不是真的)标头的GET /restricted请求来解决服务器端的这个问题。然后使用包含您的 Angular 代码的 HTML 进行响应,并在页面加载时再次请求。这将是区分显式 URL 导航和 Angular 请求的好方法,并为您的 API 提供更好的超媒体支持。Accepttext/htmlapplication/json/restrictedapplication/json

于 2015-04-21T20:41:36.057 回答