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

hfwmuf9z  于 2022-11-23  发布在  其他
关注(0)|答案(2)|浏览(121)

我使用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);
      });
  },

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

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

当我手动刷新页面时,页面被重定向。
然而,当我在身份验证后的受保护路由中时,自动重定向对this.get('session').invalidate()起作用,这将我踢出了受保护的路由。
我知道一种方法是在authenticate方法之后添加一个then(参见下面的代码),以便在该方法返回成功响应时将URL重定向到正确的URL;然而,在浏览了这么多的例子后,我发现没有人做像下面这样的事情。

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

我错过了什么吗?为什么我的路由在验证后不自动重定向?

insrf1ej

insrf1ej1#

这对我很有效:

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

dsekswqp2#

我在网上找到了一个方法!!!希望你们都喜欢它很多!!!这里我发现:https://browntreelabs.com/redirection-in-ember-simple-auth/

相关问题