JWT and Passport returns 401 React

Asked

Viewed 56 times

1

good afternoon.

I am learning JWT and Passport and I am facing problems with the same, the problem is the following, I can log in and save in Localstorage, and redirect to another page however, even entering the correct data I get a 401 (Unauthorized). I don’t know why.

My file where ta Passport and JWT:

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 do the POST for the route of Login where the Token and is redirected to the route /pageOwnerAgency, i am redirected however, 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;

Someone can help me ?

  • 1

    I was testing your code, if the user is right and the wrong password he Uga, does the following puts a Return on if (!user) {&#xA; return res.status(401).json({ message: "no such user found" });&#xA; } E forehead, see what’s returning on the console, if possible test the route with Postman, if not already done.

No answers

Browser other questions tagged

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