Home > OS >  How can I store my JWT Token in localstorage?
How can I store my JWT Token in localstorage?

Time:12-11

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 :

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

CodePudding user response:

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!

CodePudding user response:

Use cookies for more security

res.cookie("tocken", tocken, { 
        httpOnly: true
    })
  • Related