你好,我只是一个 AngularJs 初学者,想从你们那里得到一些建议/帮助!
我正在制作一个应用程序,您可以在其中通过 Cisco CMX 服务器登录并查看您在建筑物中的当前位置。 它是一个服务器,通过你连接的几个接入点的信息计算你的位置
我需要与 mongodb 通信以验证用户身份,为此我使用 token 。
当我登录时,我想使用另一个身份验证 header 转到 CMX 的 API。
但我看不出它是如何工作的。
我在运行时在我的 app.js 中设置了我的默认 header
$http.defaults.headers.common['Authorization'] = 'Bearer ' + $window.jwtToken;
当我想访问 CMX API 时,我会更改我的默认 header
$http.defaults.headers.common['Authorization'] = 'Basic AAAAAAAAAAAAAAAAAAAAA==';
但它不会成功..
通过网络服务器本身而不是客户端与 CMX 通信不是更好吗?
谢谢
最佳答案
在您的情况下,您希望拦截每个 HTTP 请求并向其注入(inject)包含自定义 token 的授权 header 。
为此,您需要使用 angularjs 拦截器。
The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor
这是一个拦截器示例,如果 token 在浏览器的本地存储中可用,它就会注入(inject) token 。
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function ($q, $location, $localStorage) {
return {
'request': function (config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers.Authorization = 'Bearer ' + $localStorage.token;
}
return config;
},
'responseError': function (response) {
if (response.status === 401 || response.status === 403) {
$location.path('/signin');
}
return $q.reject(response);
}
};
}]);
代码启发from
关于javascript - 如何在同一个 Angular JS 应用程序中使用具有不同身份验证 header 的不同 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36497284/