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?
This works for me:
this.get('session').authenticate('authenticator:jwt', username, password).then(
() => this.transitionTo("index"),
(err) => this.controller.set('error', err.error || err)
);