Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I store my JWT Token in localstorage?

userAction.js -> Frontend, Action

export const login = (userID, password) => async (dispatch) => {
    try {
        dispatch({ type: USER_LOGIN_REQUEST });
       
        const url = "http://localhost:8080/authenticate/";
        const config = {
          auth: {
            username: userID,
            password,

          },
        };
    
        const data = {};
        const response = await axios.post(
            url, 
            data, 
            config,
            
        )

        dispatch({ type: USER_LOGIN_SUCCESS, payload: config});
        
 
        if (response.status === 200) {
          // Login succeeded
          const token = response.data.token;
          console.log("TOKEN\n" + token);
          config.token = response.data.token;
          console.log(response.data.token);
          
        }
        
        localStorage.setItem("userInfo", JSON.stringify(config) );
    }

My login function in REST Server :

exports.login = async (req,res) =>{

  const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
  const [userID, password] = Buffer.from(b64auth, 'base64').toString().split(':');
  const user = await User.findOne({ userID: userID });
  if(!user) return res.status(400).send('User not found');
  const validPass = await bcrypt.compare(password, user.password);
  if(!validPass) return res.status(400).send('Incorrect Password');

  //const token = generateToken(user.userID);
  let payload = {
    userID: user.userID
  }
  const token = generateToken(userID);
  
  res.header('Authorization', 'Bearer ' + token).json(user);
  
  return token;
}

I generate my token this way :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const generateToken = (_id) => {
  console.log('Signing token for ID ', _id);
  console.log('Secret key is ', process.env.JWT_KEY);
  const token = jwt.sign({ _id}, process.env.JWT_KEY, {
    expiresIn: "30d",
  });
  console.log('Signed token: ', token);
  return token;
};

I try to store my token in my "userInfo" State .. but only username and password is displayed not token ..It works before .. but I don´t know why it´s not working anymore ^^ I´m completely at a loss

I hope someone sees the error

my Console gives me the detail:

TOKEN 
undefined

>Solution :

You are expecting response.data to be an object. In that case update your API handler to return property token in an object:

exports.login = async (req,res) =>{

  const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
  const [userID, password] = Buffer.from(b64auth, 'base64').toString().split(':');
  const user = await User.findOne({ userID: userID });
  if(!user) return res.status(400).send('User not found');
  const validPass = await bcrypt.compare(password, user.password);
  if(!validPass) return res.status(400).send('Incorrect Password');

  //const token = generateToken(user.userID);
  let payload = {
    userID: user.userID
  }
  const token = generateToken(userID);
  
  return res.header('Authorization', 'Bearer ' + token).json({ user, token });
}

Hopefully that helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading