1

I am using JWT (JSON Web Token) to authenticate user. I do include the ApplicationRouteMixin in application.js route and it supports to handle two events (success login and success logout) by default.

Now when I login with a user credential using code below,

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

The URL stay the same even the response is success and includes the valid JWT (see below).

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

When I refresh the page manually then the page get redirected.

However, when I am in the protected route after authentication, the auto redirect is working for this.get('session').invalidate() which kick me out of the protected route.

I know one walkaround is to add a then after authenticate method (see code below) to redirect the URL to the right one when there is a success response from the method; however, after browse so many examples I see no one does something like below.

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

I am missing anything here? Why my route does not auto redirect after authentication?

XY L
  • 25,431
  • 14
  • 84
  • 143

2 Answers2

0

This works for me:

this.get('session').authenticate('authenticator:jwt', username, password).then(
    () => this.transitionTo("index"),
    (err) => this.controller.set('error', err.error || err)
);
user4426017
  • 1,930
  • 17
  • 31
  • This is similar to what I have – XY L Feb 24 '17 at 15:04
  • If you do not specify where to redirect you upon successful authentication, how would your app know where to redirect you? You must add a 'then' or specify in your 'config' file the following: ENV['ember-simple-auth'] = { authenticationRoute: 'login', routeAfterAuthentication: 'index', routeIfAlreadyAuthenticated: 'about' }; – user4426017 Feb 24 '17 at 15:29
  • config inside ENV is depecated – XY L Feb 24 '17 at 15:44
  • 1
    Yeah, you are right. I just noticed the deprecation warning. I guess the only way that I have it working is by specifying a 'then'. Good luck! – user4426017 Feb 24 '17 at 15:49
0

I found out a way on the internet!!! Hope you all enjoy it a lot!!! Here where I found: https://browntreelabs.com/redirection-in-ember-simple-auth/

Luis
  • 1
  • 1