How to send a token to Header Authorization (Node/Ionic/Angular)

Asked

Viewed 485 times

0

Good afternoon,

I would like some guidance on how I could take the token being generated in my back-end (Nodejs + Express + Mongodb API) and save it in Header Authorization when the user logs in to the system.

I’ll put the Nodejs codes and the application in order to try to make my procedures clear:

The authentication and token generation part in Nodejs looks like this:

function generateToken(params = {}) {
return jwt.sign(params, authConfig.secret, {
    expiresIn: 86400, 
});
}

router.post('/authenticate', async (req, res) => { //Criando uma rota de autenticação.
const { email, senha } = req.body; //Recebendo o email e a senha do nosso corpo da requisição.
try {
    const user = await User.findOne({ email }).select('+senha'); //Faz uma verificação se o e-mail e senha existem no banco de dados.

    if (!user) { //Verifica se o usuário existe no banco de dados.
        return res.status(400).send({ error: 'Usuário não encontrado!' }); //Retorna um erro com uma mensagem.
    }

    if (!await bcrypt.compare(senha, user.senha)) { //Verifica se a senha informada é a mesma senha do cadastro do usuário.
        return res.status(400).send({ error: 'Senha inválida!' }); //Retorna um erro com uma mensagem.
    }

    user.senha = undefined; // Faz com que a senha não seja retornada com o seu valor para o usuário na sua criação.

    return res.send({ user, 
                      token: generateToken({ id: user.id })
                    });
} catch (err) {
    return res.status(401).send({ error: 'Erro ao logar usuário!' }); //Retorna um erro com uma mensagem.
}
});

My Usuarioservice.ts class that calls the route above the Nodejs is like this:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class UsuarioService {

 API_Login: string = "http://localhost:4000/auth/authenticate/";

 constructor(private http: HttpClient) { }

 authenticate(email: string, senha: string) {
   return this.http.post(this.API_Login, {email: email, senha: senha});
 }
}

In my Loginpage.TS component, which makes the Usuarioservice.ts call, the Login method looks like this:

loginUsuario() {

const email = this.loginForm.get('email').value;
const senha = this.loginForm.get('senha').value;

this.usuarioService.authenticate(email, senha)
                   .subscribe(()  => {
                     this.alertLoginSuccess();
                     this.loginForm.reset();
                     this.router.navigate(['/home']);
                   }, erro => {
                     console.log(erro);
                     this.alertLoginError();
                     this.loginForm.reset();
                   });
 }

Login works correctly, I can log into the system using the e-mail and the correct password of some user created in the database, however, I would like guidance on how I get the value of the token that is being generated in Nodejs if the user login was a success and store it in Authorization Header, because it is through this Header that the back-end does a search for the user’s Token.

Any further information, please, I am available!

Thanks for your attention!

1 answer

0

subscribe returns in the first callback, the successful response of your API simply change the following code snippet:

this.usuarioService.authenticate(email, senha)
               .subscribe((response)  => {

                 response.token //Acesso ao token retornado da sua API
                 response.user // Acesso ao usuario retornado da sua API

                 localStorage.setItem('token',response.token);
                 localStorage.setItem('user',JSON.stringfy(response.user))

                 this.alertLoginSuccess();
                 this.loginForm.reset();
                 this.router.navigate(['/home']);
               }, erro => {
                 console.log(erro);
                 this.alertLoginError();
                 this.loginForm.reset();
               });

To store the token and the user, you can use localstorage. Therefore, in other requisitions that require an authentication, just grab the token and add it to the header of your request.

You can also, leave this logic of adding the token and the user in the direct localstorage in the service layer:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { tap } from 'rxjs/operator';

@Injectable({
  providedIn: 'root'
})

export class UsuarioService {

 API_Login: string = "http://localhost:4000/auth/authenticate/";

 constructor(private http: HttpClient) { }

 authenticate(email: string, senha: string) {
   return this.http.post(this.API_Login, {email: email, senha: senha});
 }.pipe( tap( response => {
     localStorage.setItem('token',response.token);
     localStorage.setItem('user',JSON.stringfy(response.user))
  ))
}
  • Thanks for the tips Eduardo! I will try this way proposed by you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.