Use JWT to authenticate API requests using typescript

0

Speak, then I have a problem, I apologize if this problem has been solved before, but I did not find the solution; In my API I can create my token and made a middleware route for my API token

When I test in Postman everything is fine, I generate the token and the requests only return something when I put the token in the header using x-access-token.

TokenValidation

I've tried many ways I've seen on the internet, but so far nothing has helped me, could anyone give me a light?

  • token creation:

const express = require('express');
const passwordHash = require('password-hash');
const User = require('../models/user');
const jwt = require('../services/jwt');

const router = new express.Router();

// Verificação login
router.post('/login', (req, res) => {
    let query = { email: req.body.email };
    User.findOne(query, (err, user) => {
        if (err || user === null) {
            return res.status(401).send("Login inválido");
        } else {
            if (passwordHash.verify(req.body.password, user.passwordHash)) {
                var token = jwt.generateToken({ userId: user._id });
                res.set("Authorization", 'Bearer ${token}');
                const user_json = user.toJSON();
                delete user_json.passwordHash;
                return res.status(200).send([user_json,
                    {
                        message: 'Token criado',
                        token: token
                    }]);

            } else {
                return res.status(401).send("Login inválido");
            }
        }
    });
});

module.exports = router; 

And the middleware route that authenticates to token :

const express = require('express');
const Student = require('../models/student');
const jwt = require('jsonwebtoken');
const jwtKey = 'myKey';

const router = new express.Router();

//TokenValidations 
router.use( (req, res, next) => {
    var token = req.body.token || req.query.token || req.headers['x-access-token'];
    if(token) {
        jwt.verify( token, jwtKey, (err, decoded) => {
            if (err) {
                return res.status(401).send({
                    message: 'falha ao autenticar token'
                });
            } else {
                req.decoded = decoded;
                next();
            }
        });
    } else {
        return res.status(403).send({
            message: 'não há token'
        });
    }
});

I use the following function to validate the login and store the token :

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { User } from '../../models/user';
import { UserService } from '../../services/user.service';

import { environment } from '../../../environments/environment';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  showForbiddenError: boolean = false;

  isShowing = false;
  form = {  
    email: '',
    password: ''
  }

  constructor(private http: HttpClient, private userService: UserService, private router: Router) { }

  showPassword() {
    this.isShowing = !this.isShowing;
  }

  login(){
    let url = environment.apiUrl + 'login'
    this.http.post<User>(url, this.form, {observe: 'response'})
    .subscribe(response => {   
      let user = response.body[0];
      user.token = response.body[1].token;
      this.userService.login(user);
      this.router.navigate(['admin/home']);
      this.showForbiddenError = false;
      console.log(user);
    }, catchError =>{
      catchError = catchError.status;
      this.showForbiddenError = true;
      console.log('O servidor retornou o erro: ${catchError}');    
    });
  }

  ngOnInit(){
    const user = this.userService.getUser();
    if(user && user.token){
      this.router.navigate(['admin']);
    }
  }
}
    
asked by anonymous 20.07.2018 / 19:13

0 answers