JWT and Passport returns 401 React

1

Good afternoon.

I am learning JWT and Passport and am experiencing problems with the same, the problem is this, I can login and save in LocalStorage, and redirect to another page however, even entering the correct data I get a 401 (Unauthorized) . I do not know why.

My file where Passport and JWT are:

const express = require('express');
const bodyParser = require('body-parser');
const _ = require("lodash");

const app = express();

const jwt = require('jsonwebtoken');
const passport = require('passport');
const passportJWT = require('passport-jwt');

const ExtractJwt = passportJWT.ExtractJwt;
const JwtStrategy = passportJWT.Strategy;

app.use(passport.initialize());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

var jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
jwtOptions.secretOrKey = 'tasmanianDevil';

var strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {
  console.log('payload received', jwt_payload);
  var user = users[_.findIndex(users, { id: jwt_payload.id })];
  if (user) {
    next(null, user);
  } else {
    next(null, false);
  }
});

passport.use(strategy);

var users = [
  {
    id: 1,
    name: 'jonathanmh',
    password: '%2yx4'
  },
  {
    id: 2,
    name: 'test',
    password: 'test'
  }
];

app.post("/login", function (req, res) {
  if (req.body.name && req.body.password) {
    var name = req.body.name;
    var password = req.body.password;
  }
  var user = users[_.findIndex(users, { name: name })];
  if (!user) {
    res.status(401).json({ message: "no such user found" });
  }

  if (password === user.password) {
    var payload = { id: req.body.id };
    var token = jwt.sign(payload, jwtOptions.secretOrKey);
    res.send({ message: "ok", token: token });
  } else {
    res.status(401).json({ message: "passwords did not match" });
  }
});

app.get('/pageOwnerAgency', passport.authenticate('jwt', { session: false }), (req, res) => {
  res.send({message: 'oi'})
});

require('./server/routes')(app);
require('./server/cors')(app);

module.exports = app;

My file where I make POST for the Login route where the Token is generated and is redirected to the /pageOwnerAgency route, I'm redirected by, I get on the console a 401:

import React from 'react';
import axios from 'axios';
import Body from '../components/Body/Body';

import { ContainerLogin, InputLogin, ButtonLogin } from './styled.js';

import { Redirect } from 'react-router-dom'

class Login extends React.Component {
  constructor() {
    super();

    this.state = {
      name: '',
      password: '',
      teste: false,
    }
  }

  handleInput = (e) => {
    let value = e.target.value;

    this.setState({ [e.target.name]: value })
  }

  handleLogin = () => {
    axios.post('/login', { name: this.state.name, password: this.state.password })
      .then(res => {
        localStorage.setItem('jwt', res.data.token);
        window.location.reload();
      })
      .catch(error => console.log(error.response.data.message))
  }

  render() {
    if (localStorage.getItem('jwt')) return <Redirect to="/pageOwnerAgency" />

    return (
      <Body>
        <ContainerLogin>
          <InputLogin onChange={this.handleInput} name="name" placeholder="USERNAME" />
          <InputLogin onChange={this.handleInput} name="password" placeholder="PASSWORD" type="password" />
          <ButtonLogin onClick={this.handleLogin}> Login </ButtonLogin>
        </ContainerLogin>
      </Body>
    )
  }

}
export default Login;

Can anyone help me?

    
asked by anonymous 29.08.2018 / 20:43

0 answers