【问题标题】:setting the access token on every ajax request在每个 ajax 请求上设置访问令牌
【发布时间】:2016-01-08 12:39:04
【问题描述】:

我正在使用新版本的 ember-simple-auth,它不再自动将访问令牌添加到发送到服务器的 ajax 请求中。

我正在使用 oauth2 身份验证,由于文档不正确,我不知何故无法弄清楚为我所做的每个 ajax 请求设置标头令牌的正确方法是什么以及在哪里。

这段代码应该在自定义授权人的授权功能下还是在其他地方?

this.get('session').authorize('authorizer:some-authorizer', (headerName, headerValue) => {
  xhr.setRequestHeader(headerName, headerValue);
});

任何有关正确设置的信息将不胜感激!

【问题讨论】:

    标签: ember.js ember-simple-auth


    【解决方案1】:

    你可以这样做:

    let userToken;
    this.get('session').authorize('authorizer:some-authorizer', (headerName, headerValue) => {
        userToken = headerValue;
    });
    
    $.ajax({
        url: "Your Url",
        // ...
        beforeSend: function(xhr){
            xhr.setRequestHeader('Authorization', userToken);
        }
    })
    

    如果您不想在每个请求上都这样做,您可以在某处创建自己的 customAjaxCall 并使用那个:

    export default function customAjaxCall(session, url) {
        let userToken;
        session.authorize('authorizer:some-authorizer', (headerName, headerValue) => {
            userToken = headerValue;
        });
    
        return $.ajax({
            url: url,
            dataType: 'json',
            contentType: 'application/json; charset=UTF-8',
            // ...
            beforeSend: function(xhr){
                xhr.setRequestHeader('Authorization', userToken);
            }
        })
    }
    

    【讨论】:

      【解决方案2】:

      我们在我们的应用程序中使用自定义适配器,适配器看起来像这样

      import DS from "ember-data";
      import Ember from "ember";
      import App from '../app';
      
      export
      default DS.RESTAdapter.extend({
          namespace: 'data',
          host: App.hostUrl,
          ajax: function (url, type, hash) {
              hash = hash || {};
              hash.headers = hash.headers || {};
              hash.headers['Authorization'] = 'Token token=' + App.access_token;
              hash.crossDomain = true;
              return this._super(url, type, hash);
          }
      });
      

      使用的所有其他模型适配器都扩展了此适配器,例如。

      import ApplicationAdaper from './application';
      
      export default ApplicationAdaper.extend({
         ...
      });
      

      参考和更多信息检查 RESTAdapter Header Customization http://emberjs.com/api/data/classes/DS.RESTAdapter.html

      【讨论】:

      • 不错。这个Adapter的ajax调用怎么用?
      • 指定的标头会自动添加到给定模型适配器进行的每个 ajax 调用
      猜你喜欢
      • 2018-09-20
      • 2013-04-21
      • 2019-02-20
      • 2017-10-15
      • 2022-12-15
      • 1970-01-01
      • 2014-07-17
      • 2016-02-22
      • 2011-09-19
      相关资源
      最近更新 更多