How to Resolve 401 unAuthorized error even though Tokens and everything is set? and postman returns no issue at all while testing -MERN Stack

Viewed 5640

i am new to react and I've been trying to make this api work,(following you tube tutorial), when i test the routes via postman the response i receive is 'OK-working' but then when i try to login from my react app, it turns to unauthorized, i don't know how to deal with this *** i have done everything i could possibily upto my understanding ***, I've explored as much stack Overflow as i could as well as Googled it but still not found something understandable enough.

p.s this is very critical issue for me as this is part of my web Class at college and it holds a great deal of grades!

Attaching the link to github directory as well in case you need it : https://github.com/nescafestar/twitter-clone

this is my AuthActions.js file

```
//authAction.js

import axios from 'axios';
import {GET_ERRORS, SET_CURRENT_USER} from '../constants';
import setAuthHeader from '../utils/setAuthHeader'

export const registerUser = (userData, history) => dispatch => {
    axios.post('http://localhost:5000/api/users/register', userData,{
        headers: {
          'Authorization': 'Bearer'+ localStorage.getItem('jwtToken')
        }
      })
        .then(res => {
            console.log('----> registering')
            const { token } = res.data 
            localStorage.setItem('jwtToken', token)
            if(token){
                axios.defaults.headers.common['Authorization']='Bearer : '+ token
            }
            history.push('/')})
        .catch(err => dispatch({
            type: GET_ERRORS,
            payload: err.response.data
        }))
}

export const loginUser = (userData) => dispatch => {
    axios.post('http://localhost:5000/api/users/login',userData,{
        headers: {
          'Authorization': 'Bearer : ' +localStorage.getItem('jwtToken')
        }
      })
    .then(res => {
        // console.log(userData)    
            const { token } = res.data 
            localStorage.setItem('jwtToken', token)
            if(token){
                axios.defaults.headers.common['Authorization']='Bearer : ' +token
            }
            console.log('---> hit dispatch')
            dispatch(getCurrentUser())
        })
        .catch(err => {
            // console.log(err);
            // dispatch({
            //  type: GET_ERRORS,
            //  payload: err.response.data
            // })
        })
}

export const getCurrentUser = () => dispatch => {
    axios.get('http://localhost:5000/api/users',{
        headers: {
            'Authorization': 'Bearer : ' +localStorage.getItem('jwtToken')
        }
    })
    .then(res => dispatch(setCurrentUser(res.data)))
    .catch(err => dispatch({
        type: GET_ERRORS,
        payload: err.response.data
    }))
    
}


export const setCurrentUser = (data) => {
    console.log('----> setting user!')
    return {
        
        type: SET_CURRENT_USER,
        payload: data
    }
}

export const logoutUser=()=>dispatch=>{
    localStorage.removeItem('jwtToken')
    setAuthHeader()
    dispatch(setCurrentUser())
}
```

this is the set Auth Header one:
```
import axios from 'axios'
// const jsonwebtoken=require('jsonwebtoken')


export default function(token){

    console.log(token)
    if(token){
        console.log('Token has been set-properly')
       return axios.defaults.headers.common['Authorization']='Bearer'+ token
    }else{
       return axios.defaults.headers.common['Authorization']=null

    }
}

```

and lastly this is my POST.js file which is also returning the same issue of being unAuthorized


    import axios from 'axios'
    // const jsonwebtoken=require('jsonwebtoken')
    
    
    export default function(token){
    
        console.log(token)
        if(token){
            console.log('Token has been set-properly')
           return axios.defaults.headers.common['Authorization']='Bearer'+ token
        }else{
           return axios.defaults.headers.common['Authorization']=null
    
        }
    }
    ``` ```
   ////////////////////////*** ROUTER ***
    ``` ```
// also the Routes/User.js file in case someone wants to know about it as well
    const router = require("express").Router();
    const User = require("../models/User");
    const jwt=require('jsonwebtoken');
    const passport = require("passport");
    //validation
    const validateRegisterInput = require("../validation/register");
    const validateLoginInput = require("../validation/login");
    //handling password hasing
    const bcrypt = require("bcryptjs");
    // const utils = require("../utils/utils");
    
    //routing requests
    
    //handling post request
    router.route("/register").post((req, res) => {
      const { isValid, errors } = validateRegisterInput(req.body);
      if (!isValid) {
        return res.status(404).json(errors);
      }
      //test arguments
      // return res.send('OKKKK!!');
    
      //register user is it does not exist in db
      User.findOne({ email: req.body.email }).then((user) => {
        if (user) {
          errors.email = "Email already Registered!";
          return res.status(404).json(errors);
        }
    
        bcrypt.genSalt(10, function (err, salt) {
          bcrypt.hash(req.body.password, salt, function (err, hash) {
            //adding new User to DB is Not Exist
            const newMember = new User({
              username: req.body.username,
              email: req.body.email,
              password: hash,
            });
            newMember
              .save()
              .then((newMember) => res.json(newMember))
              .catch((err) => console.log(err));
          });
        });
      });
    }); //register route ends
    
    //Login Route
    router.route('/login')
        .post((req, res) => {
            const { errors, isValid } = validateLoginInput(req.body)
    
            if (!isValid) {
                return res.status(404).json(errors)
            }
    
            User.findOne({ email: req.body.email })
                .then(user => {
                    if (!user) {
              errors.email = 'User not found/not exist'
                        return res.status(404).json(errors)
                    } else {
              
              bcrypt.compare(req.body.password, user.password)
                        .then(isMatch => {
                            if (isMatch) {
                                const token = jwt.sign({ id: user._id }, process.env.SECRET, { expiresIn: '1d' }, function (err, token) {
                                    return res.json({
                                        success: true,
                                        token: token
                                    })
                                })
                            } else {
                                errors.password = 'Password is incorrect'
                                return res.status(404).json(errors)
                            }
                        })
                    
                        }
                })
    })
    
    
    //returning route for logged in user 
    router.route('/')
        .get( passport.authenticate('jwt', { session: false }),(req, res) => {
            console.log('here! in home redirect')
            res.json({
                _id: req.user._id,
                email: req.user.email,
                username: req.user.username,
                followers: req.user.followers,
                following: req.user.following
            })
    })
    module.exports = router;

1 Answers

You are not populating the Authorization header consistently or correctly. Assume your jwtToken value is AAAA for simplicity. In some cases you send BearerAAAAAA, in others you send Bearer : AAAA. The standard should be to use the string "Bearer", followed by one space, followed by the base64 encoding of the token (Bearer AAAA). See the RFC for more information: https://www.rfc-editor.org/rfc/rfc6750

When setting the header, you could use something like this:

const token = localStorage.getItem('jwtToken') //Or however you choose to get it
const headers = {
  Authorization: `Bearer ${token}`
}
Related