如何使用ember-simple-auth进行身份验证后自动重定向

时间:2017-02-24 12:00:15

标签: ember.js ember-simple-auth

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

现在,当我使用下面的代码登录用户凭证时,

  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(),这会让我离开受保护的路由。

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

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

我在这里遗失什么?为什么我的路由在认证后不会自动重定向?

2 个答案:

答案 0 :(得分:0)

这对我有用:

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

答案 1 :(得分:0)

我在互联网上找到了一种方法!!!希望大家都喜欢!!!我在这里找到的地方:https://browntreelabs.com/redirection-in-ember-simple-auth/

相关问题