【问题标题】:Ember simple auth doesn't send auth header to apiEmber 简单身份验证不会将身份验证标头发送到 api
【发布时间】:2017-02-18 00:55:13
【问题描述】:

我正在尝试在我的 ember 应用程序中进行授权。

它在客户端工作,但 ember 不会将 Bearer 令牌附加到 api 请求。

我的适配器

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
 host: 'http://localhost/money-app-api/web/app_dev.php/api',
 authorizer: 'authorizer:application'
});

我的授权人:

import Ember from 'ember';
import OAuth2Bearer from 'ember-simple-auth/authorizers/oauth2-bearer';
const { isEmpty } = Ember;

export default OAuth2Bearer.extend({
authorize(data, block) {
const accessToken = data['access_token'];
if (!isEmpty(accessToken)) {
  block('Authorization', `Bearer ${accessToken}`);
}

授权器中的accessToken存在且正确。 我的 api 也是正确的,我用 Postman 测试过。

【问题讨论】:

  • 请在标题中描述您的问题。

标签: ember.js ember-data ember-simple-auth


【解决方案1】:

我唯一的问题是我在 api 的接受标头中没有 authorization

allow_headers: ['origin', 'X-Custom-Auth', 'Content-Type', 'Authorization']

这很奇怪,因为 Postman 测试时一切正常。

【讨论】:

    【解决方案2】:

    我正在给你写一个完整的教程,请按照它来做,希望它对你有用。

       //folders and files tree
        adapters
        --- application.js
        authenticators
        --- oauth2.js
        authorizers
        ---- oauth2-bearer.js
    

    适配器/application.js

    import DS from 'ember-data';
    import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
    
    export default DS.JSONAPIAdapter.extend(DataAdapterMixin,{
      authorizer: 'authorizer:oauth2-bearer',
      host: 'http://localhost/money-app-api/web/app_dev.php',
      namespace: 'api'
    });
    

    身份验证器/oauth2.js

    import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
    
    export default OAuth2PasswordGrant.extend({
      serverTokenEndpoint: 'http://localhost/money-app-api/web/app_dev.php/token'
    });
    

    授权者/oauth2-bearer.js

    export { default } from 'ember-simple-auth/authorizers/oauth2-bearer';
    

    所以现在在您的路线中,application.js,您可以使用以下代码:这仅用于演示目的,您需要根据需要进行修改。

      this.get('session').authorize('authorizer:oauth2-bearer', (headerName, headerValue) => {
              headers[headerName] = headerValue;
            });
    

    我正在 route/application.js 中编写身份验证以澄清更多信息。在此示例中,我根据已验证的会话获取帐户和用户信息。

    import Ember from 'ember';
    import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
    import config from '../config/environment';
    
    export default Ember.Route.extend(ApplicationRouteMixin, {
    
      model() {
        return Ember.RSVP.hash({
          account: new Ember.RSVP.Promise((resolve, reject) => {
    
            if (!this.get('session.isAuthenticated')) {
              resolve({});
              return;
            }
    
            let store = this.store,
              session = this.get('session');
    
            let headers = {};
    
            this.get('session').authorize('authorizer:oauth2-bearer', (headerName, headerValue) => {
              headers[headerName] = headerValue;
            });
    
            return Ember.$.ajax(config.apiUrl + '/api/account', {
              headers: headers
            }).then(data => {
              if (data) {
                store.pushPayload(data);
                resolve(store.peekRecord('user', data.data.id));
              } else {
                reject({});
                session.invalidate();
              }
            }).fail(() => {
              session.invalidate();
            });
          })
        });
      },
      sessionAuthenticated() {
        this.refresh();
        this._super();
      }
    });
    

    我希望,这可以解决您的问题。

    重要提示:

     The REST adapter allows your store to communicate with an HTTP server by
      transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
      should use the REST adapter.
      ### Headers customization
      Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary
      headers can be set as key/value pairs on the `RESTAdapter`'s `headers`
      object and Ember Data will send them along with each ajax request.
      ```app/adapters/application.js
      import DS from 'ember-data';
      export default DS.RESTAdapter.extend({
        headers: {
          "API_KEY": "secret key",
          "ANOTHER_HEADER": "Some header value"
        }
      });
      ```
      `headers` can also be used as a computed property to support dynamic
      headers. In the example below, the `session` object has been
      injected into an adapter by Ember's container.
      ```app/adapters/application.js
      import DS from 'ember-data';
      export default DS.RESTAdapter.extend({
        headers: Ember.computed('session.authToken', function() {
          return {
            "API_KEY": this.get("session.authToken"),
            "ANOTHER_HEADER": "Some header value"
          };
        })
      });
      ```
    

    Source

    【讨论】:

    • 我已经拥有它并且它为我工作。但我的问题是 ember 没有将标头附加到 json 适配器
    • 我刚刚添加了在适配器中发送标头的提示,这应该可以帮助您解决问题。试一试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2019-02-21
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多