微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我应该在哪里将Bearer令牌注入AngularJS中的$http?

在接受用户凭证后,我获取了承载令牌[1]并更新了认头:
$http.defaults.headers.common.Authorization = "Bearer #{data.access_token}"

这是在$scope.signIn()方法的末尾完成的.这些令牌在整个会话期间是否会持久存在,还是应该使用其他技术?

[1] https://github.com/doorkeeper-gem/doorkeeper/wiki/Client-Credentials-flow

app.run run = ($http,session) ->
    token = session.get('token')
    $http.defaults.headers.common['Authorization'] = token
解决此问题的一个方法是创建一个authInterceptor工厂,负责将标头添加到所有$http请求:
angular.module("your-app").factory('authInterceptor',[
  "$q","$window","$location","session",function($q,$window,$location,session) {
    return {
      request: function(config) {
        config.headers = config.headers || {};
        config.headers.Authorization = 'Bearer ' + session.get('token'); // add your token from your service or whatever
        return config;
      },response: function(response) {
        return response || $q.when(response);
      },responseError: function(rejection) {
        // your error handler
      }
    };
  }
]);

然后在你的app.run中:

// send auth token with requests
$httpProvider.interceptors.push('authInterceptor');

现在,所有使用$http(或$resource资源)发出的请求都将沿授权标头发送.

这样做而不是更改$http.defaults意味着您可以更好地控制请求和响应,此外您还可以使用自定义错误处理程序或使用您想要的任何逻辑来确定是否应该发送身份验证令牌.

原文地址:https://www.jb51.cc/angularjs/141224.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐