【问题标题】:How to auto redirect after authenticate using ember-simple-auth如何在使用 ember-simple-auth 进行身份验证后自动重定向
【发布时间】:2017-07-15 06:07:20
【问题描述】:

我正在使用 JWT (JSON Web Token) 对用户进行身份验证。我确实在application.js 路由中包含了ApplicationRouteMixin,它默认支持处理两个事件(成功登录和成功注销)。

现在,当我使用以下代码使用用户凭据登录时,

  login(credential) {
    const authenticator = 'authenticator:jwt';
    const session = this.get('session');

    session.authenticate(authenticator, credential)
      .catch(() => {
        const errorMessage = "Wrong email or password. Please try again!";
        this.set('errorMessage', errorMessage);
      });
  },

即使响应成功,URL 也会保持不变,并包含有效的 JWT(见下文)。

{"jwt":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0ODg1NDIyMTcsInN1YiI6Mn0.Ma0ZtLWhoO1mb5cluGJZcKuHb-J2ZJdZOd3AFhVI258"}

当我手动刷新页面时,页面会被重定向。

但是,当我在身份验证后处于受保护的路由中时,自动重定向对this.get('session').invalidate() 起作用,这会将我踢出受保护的路由。

我知道一种解决方法是在authenticate 方法之后添加一个then(请参见下面的代码),以便在该方法成功响应时将URL 重定向到正确的方法;但是,在浏览了这么多示例后,我发现没有人会像下面那样做。

    session.authenticate(authenticator, credential)
      .then(() => {
        this.transitionTo('browse');
      })
      .catch(() => {
        const errorMessage = "Wrong email or password. Please try again!";
        this.set('errorMessage', errorMessage);
      });

我在这里遗漏了什么?为什么我的路由在认证后没有自动重定向?

【问题讨论】:

  • 也许你在登录路径中混入了AuthenticatedRouteMixin?!
  • sessionAuthenticated 钩子中有一个异常。请检查那里抛出的错误
  • 我的控制台没有任何异常。
  • 您使用哪个版本的 ESA?
  • 最新版本DEBUG: Ember Simple Auth : 1.2.0

标签: ember.js ember-simple-auth


【解决方案1】:

我在网上找到了一个方法!!!希望大家玩的开心!!!我在这里找到:https://browntreelabs.com/redirection-in-ember-simple-auth/

【讨论】:

    【解决方案2】:

    这对我有用:

    this.get('session').authenticate('authenticator:jwt', username, password).then(
        () => this.transitionTo("index"),
        (err) => this.controller.set('error', err.error || err)
    );
    

    【讨论】:

    • 这个和我的差不多
    • 如果您没有指定在成功验证后将您重定向到哪里,您的应用如何知道将您重定向到哪里?您必须添加一个 'then' 或在 'config' 文件中指定以下内容:ENV['ember-simple-auth'] = { authenticationRoute: 'login', routeAfterAuthentication: 'index', routeIfAlreadyAuthenticated: 'about' };
    • ENV 内的配置已被弃用
    • 是的,你是对的。我刚刚注意到弃用警告。我想我让它工作的唯一方法是指定一个'then'。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    相关资源
    最近更新 更多