我正在使用 AngularJS 构建一个 SPA,并与服务 (JAVA) 进行通信。
当用户发送他的用户名/密码时,服务会发回:访问 token 和刷新 token 。我正在尝试处理:如果我收到状态 401 的响应,请发回刷新 token ,然后再次发送您的最后一个请求。我尝试通过包含 $http 来做到这一点,但是 Angular 不允许我将其包含在这个拦截器中。有没有办法使用我收到的响应参数重新创建原始请求?
类似于:
- 我收到 401
- 保存我的请求
- 如果我有刷新 token ,请发送该刷新 token
- 成功后重新发送我的请求
错误时重定向到/登录页面
'use strict'; angular.module('testApp') .factory('authentificationFactory', function($rootScope, $q, $window, $location, CONF) { return { request: function(config) { config.headers = config.headers || {}; if ($window.sessionStorage.token) { config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token; } console.log(config); $rootScope.lastRequest = config; return config; }, response: function(response) { console.log($rootScope.lastRequest); if (response.status === 401) { if ($window.sessionStorage.refreshToken) { //Save, request new token, send old response //if it fails, go to login $location.url('/login'); } else { $location.url('/login'); } } return response || $q.when(response); } }; });
额外问题(主要问题更重要):有 2 个移动应用程序也将连接到我的服务,当我从我的网络应用程序登录,并在几分钟后从我的移动应用程序登录时,移动应用程序需要新的刷新 token 和我的网络应用程序的刷新 token 不再有效。处理这个问题的最佳选择是什么?
感谢您的宝贵时间, 最好的问候
最佳答案
看看这个:https://github.com/witoldsz/angular-http-auth .
他使用缓冲区在身份验证后重放请求。
关于javascript - AngularJS - 处理刷新 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23366678/