You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Ember Simple Auth自定义Authenticator的restore()恢复刷新会话?

Ember Simple Auth v5.0.0页面刷新时restore()方法传入空data的问题

我跟着YouTube教程入门Ember Simple Auth,除页面刷新场景外所有功能正常工作。自定义Authenticator本应在页面刷新时调用restore()方法从CookieStore中获取用户令牌,但实际传入该方法的data参数为空对象(console.log输出为{}),仿佛程序不知道从CookieStore中填充data。我尝试调整config/environment.js中的设置,但未找到Ember Simple Auth完善的配置文档,当前使用版本为v5.0.0。

登录后的Cookie内容

编码后内容:

ember-simple-auth-session=%7B%22authenticated%22%3A%7B%22authenticator%22%3A%22authenticator%3Atoken%22%7D%2C%22token%22%3A%22secret%20token%22%7D

解码后内容:

{"authenticated":{"authenticator":"authenticator:token"},"token":"secret token"}

自定义Authenticator代码(app/authenticators/token.js)

import Base from 'ember-simple-auth/authenticators/base';
import { inject as service } from '@ember/service';

export default class CustomAuthenticator extends Base {
  @service router;
  @service session;

  restore(data) {
    console.log('Restore');
    console.log(data);
    const { token } = data;

    if(token) {
      return data;
    }
    else {
      throw 'no valid session data';
    }
  }

  async authenticate(userData) {
    let response = await fetch('http://localhost:5000/users/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userData),
    });

    if(response.ok) {
      response.json().then((data) => {
        const { token } = data;
        this.session.set('data.token',token);

        console.log(this.session);
        this.router.transitionTo('user', data.id);
      });
    } 
    else {
      let error = await response.text();
      throw new Error(error);
    }
  }

  invalidate() {
    return new Promise((resolve, reject) => {
      resolve();
    });
  }
}

Session Store代码(session-stores/application.js)

import CookieStore from 'ember-simple-auth/session-stores/cookie';

export default class ApplicationSessionStore extends CookieStore {}

我期望从Cookie中提取token字段,按理解该字段应传入restore(data),但console.log(data)输出为空对象,data.token为undefined,请问下一步该如何处理?


内容的提问来源于stack exchange,提问作者Dean Longmire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 05:07:40