首页 > 解决方案 > 如何在 ember-simple-auth 中替换授权方法

问题描述

我正在尝试重构我的 Ember 验收测试以不使用已弃用 authorize的方法,因为它会引发警告:

The `authorize` method should be overridden in your application adapter

我检查了docs和许多其他来源,但它们实际上并没有解释如何迁移我的代码。这是我目前所拥有的:

// projectname/app/pods/login/controller.js (excerpt)
export default Controller.extend({
    session: service(),
    sessionToken: null,

    onSuccess: function(res) {
    res = res.response;
        this.set('sessionToken', res.session);
        if (res.state === "authenticated") {
            document.cookie = "token="+res.session+";path=/;";
            var authOptions = {
                success: true,
                data : {
                    session : res.session,
                }
            };
            this.get('session').authenticate("authenticator:company", authOptions);
        }
    }
});

这一定是我要摆脱的部分:

// project/app/adapters/application.js (excerpt)
export default DS.RESTAdapter.extend(DataAdapterMixin, {
    authorize(xhr) { // This is deprecated! I should remove it
        let sessionToken = this.get('session.data.authenticated.session');
        if (sessionToken && !isEmpty(sessionToken)) {
            xhr.setRequestHeader('Authorization', "Token " + sessionToken);
        }
    },
});

这是我的测试:

import { test, module } from 'qunit';
import { visit, currentURL, find, click, fillIn } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import { authenticateSession} from 'ember-simple-auth/test-support';

module('moduleName', function(hooks) {
    setupApplicationTest(hooks);

    test('moduleName', async function(assert) {
        // await authenticateSession(this.application); // Never works
        // await authenticateSession(); // Never works
        await authenticateSession({
            authenticator: "authenticator:company"
        }); // Works slightly more?
        await visit('/my/other/page');
        await assert.equal(currentURL(), '/my/other/page');
    });
});

删除该authorize方法并尝试任一注释掉的方法会产生:

Error: Assertion Failed: The `authorize` method should be overridden in your application adapter. It should accept a single argument, the request object.

如果我将authenticator块用作 arg,那么无论该authorize方法是否存在,我都会得到:

    actual: >
        /login
    expected: >
        /my/other/page

我认为,这是因为它没有登录。

authorize方法留在那里,并尝试注释的方法会产生:

Error: Browser timeout exceeded: 10s

标签: ember.jsember-simple-authember-testing

解决方案


根据您在上面链接的文档:要替换应用程序中的授权者,只需从会话服务中获取会话数据并将其注入到需要的地方。

由于您需要Authorization标题中的会话数据,因此您的用例的可能解决方案可能如下所示:

export default DS.RESTAdapter.extend(DataAdapterMixin, {
    headers: computed('session.data.authenticated.session', function() {
      const headers = {};
      let sessionToken = this.get('session.data.authenticated.session');
      if (sessionToken && !isEmpty(sessionToken)) {
        headers['Authorization'] = "Token " + sessionToken;
      }

      return headers;
    })
});

这应该允许您动态设置Authorization标题,而无需通过该authorize方法进行。


推荐阅读