【问题标题】:How to use $http inceptor to automatically attach the token to request如何使用 $http inceptor 自动附加令牌到请求
【发布时间】:2023-04-08 10:04:01
【问题描述】:

我正在开发一种身份验证机制

我在服务器端使用 nodejs,成功登录后我正在生成 jwt 令牌

如何在使用 Angularjs 构建的客户端的后续请求中使用生成的令牌

*成功登录后,我使用生成的令牌将用户重定向到主页,但我不明白如何前后使用生成的令牌并提供 api 调用

【问题讨论】:

  • 显示您尝试过的内容。您是否已经在客户端拥有令牌?
  • 是的,我在客户端有令牌
  • router.post('/login', function(req, res, next) { passport.authenticate('login', function(err, user, info) { if (err) { return next (err) } if (!user) { return res.json(401, { error: 'message' }); } //用户已正确验证,因此我们创建了 JWT 令牌 var token = jwt.sign(user,'zendynamixy ', { expiresInMinutes: 1440 // 24 小时后过期 }); // 以 JSON 格式返回包含 token 的信息 res.redirect("/?token=" + token); })(req, res, next); }) ;
  • ...通过编辑问题

标签: angularjs node.js jwt passport-local


【解决方案1】:

将令牌存储在服务中,我们称之为:authService。

然后,在模块的 .config 中,注入 $httpProvider 并添加:

    $httpProvider.interceptors.push('yourInterceptor');

然后在某个地方(在同一个文件或另一个文件中,没关系),声明一个服务调用'yourInterceptor':

angular
    .module('yourModule')
    .factory('yourInterceptor', yourInterceptor);

function yourInterceptor(authService) {
    return {
       request: function(config) {
          // config describe the call that will be made
          // you can modify the url, the headers...etc
          // for example
          config.headers.Authorization = "Bearer " + authService.myWebToken;

          return config;
       }
    }
}

注意,拦截器也可以用来拦截requestError、response、responseError。见https://docs.angularjs.org/api/ng/service/$http

【讨论】:

  • 感谢您的快速回复,我正在服务器端生成 jwt 令牌,然后像这样 res.redirect("/?token=" + token);我如何在客户端的请求中使用此令牌
  • 登录成功后req是这样的localhost:8006/…
  • 当用户登录时,作为响应发送 jwt.在角度方面,将其存储在服务中(请参阅上面的答案),然后将其注入每个请求的标头中。在服务器端,对于每个请求,检查 jwb。你有一些 npm 包可以在服务器端帮助你(我喜欢这个:github.com/auth0/express-jwt),但这是另一回事,因为你的问题是关于客户端的;)
猜你喜欢
  • 1970-01-01
  • 2019-10-01
  • 2020-11-19
  • 2016-08-29
  • 1970-01-01
  • 2019-12-20
  • 2017-04-30
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多