Answer the question
In order to leave comments, you need to log in
How to correctly transfer JWT from the server to the client during authorization?
Good day to all! There was such a question, I do authorization for the application as follows:
the user fills out the form (email and password), the submit button sends the data to the server using XHR, the server receives the data, the passport.authenticate('local', {...}) function fires, when a valid email and password are entered, the function generates a JWT , which I pass to ctx.body so that when the 'load' event is triggered, the XHR function will run a callback in which I will intercept the JWT from the server and save it to localStorage, so that later when I go to the page ' /chat' pass my jwt to the socketIo-jwt module. The problem arose in the fact that if I call the ctx.redirect ('/chat') method in the passport.authenticate () function after passing the JWT, then in the XHR function on the client I receive not a token, but a chat.pug page
Tell me what I'm doing wrong or how can I organize the code so that I can send a token to the client and automatically redirect to the next page?
// сервер
login: async function (ctx, next) {
console.log('мы в функцию логин заходим?');
console.log(ctx.request.body);
await passport.authenticate('local', {session: false}, async function (err, user) {
if (!user) {
console.log(`не видим юзера`);
ctx.redirect('/login');
} else {
console.log(`видим юзера`);
const token = await user.createJWT(user.email, user._id, config.get('JWTSecret'));
ctx.status = 200;
ctx.body = {userName: user.displayName, token: token}; /* если передаю просто ctx.body -- на клиенте получаю токен*/
ctx.redirect('/chat'); /* если оставляю метод ctx.redirect() -- на клиент уходит сам файл chat.pug*/
}
}) (ctx, next);
// клиент
function logIn () {
const candidate = {
email: document.getElementById('inputEmail').value.trim(),
password: document.getElementById('inputPassword').value.trim()
}
let xhr = new XMLHttpRequest();
xhr.open('post', '/login', true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.addEventListener('load', () => {
const dataFromServer = JSON.parse(xhr.response);
localStorage.setItem('token', dataFromServer.token);
alert(`welcome ${dataFromServer.userName}`);
});
xhr.send(JSON.stringify(candidate));
}
Answer the question
In order to leave comments, you need to log in
you need to do a redirect on the client side, if a token has arrived, then do location = "/chat"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question