0

I have node.js package which uses rest api in ubuntu. When I login, this server (node package) gives me a token in json body. So when I want to do something (any request) in server I am using this token. But there is an error when I try to compare the token server gave with login and the token that client send to server.

The code to get token from the server:

router.post('/login',(req,res)=>{ 
    const name = req.body.name;
    const password = req.body.password;
    console.log("Login request by "+name+" with password: "+password);
    if(name == "asdasd" && password == "asdadsad"){
      console.log("Auth succesful");
      const token = jwt.sign(
        {
          user: name,
          password: password
        },
        process.env.JWT_KEY,
        {
          expiresIn: "1h"
        }
      )
      return res.status(200).json({
        message:"Auth succesful",
        token: token
      });
    }else {
      return res.status(401).json({
        message:"Auth failed :("
      })
    }
})

The code to make request with the given token:

router.post('/add',checkAuth,(req,res,next)=>{ 
    console.log('haha');
    const { 
        fname, mname, lname, birthdate, created, updated, sex, place, title_id
        } = req.body
    pool.query(`INSERT INTO users (
        fname, mname, lname, birthdate, created, updated, sex, place, title_id
        ) VALUES ($1, $2,$3, $4,$5, $6,$7, $8,$9)`, [
        fname, mname, lname, birthdate, created, updated, sex, place, title_id
        ], (error, result) => {
      if (error) {throw error}
      res.status(201).send(`User added with ID: ${result.insertId}`)
    })
})

The code mentioned as checkAuth above:

const jwt = require('jsonwebtoken')

module.exports = (req,res,next) =>{
    try{
        const decoded = jwt.verify(req.headers.authorization, process.env.JWT_KEY);
        req.userData = decoded;
        next();
    }catch (error) {
        return res.status(401).json({
            message: "Auth failed"
        });
    }
}

nodemon.json file:

{
    "env": {
        "JWT_KEY": "secret"
    }
}

This is the json response from the server I got when I connect to server with postman or with android studio:

{
    "message": "Auth failed"
}

This is the result of consol.log(process.env);

Object {ALLUSERSPROFILE: "C:\ProgramData", AMD_ENTRYPOINT: "vs/workbench/services/extensions/node/extensionHos…", APPDATA: "C:\Users\aydogan\AppData\Roaming", APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL: "true", CommonProgramFiles: "C:\Program Files\Common Files", …}
check-auth.js:6
[[StableObjectId]]:2
ALLUSERSPROFILE:"C:\ProgramData"
AMD_ENTRYPOINT:"vs/workbench/services/extensions/node/extensionHostProcess"
APPDATA:"C:\Users\aydogan\AppData\Roaming"
APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL:"true"
CommonProgramFiles:"C:\Program Files\Common Files"
CommonProgramFiles(x86):"C:\Program Files (x86)\Common Files"
CommonProgramW6432:"C:\Program Files\Common Files"
COMPUTERNAME:"AYDOGAN"
ComSpec:"C:\WINDOWS\system32\cmd.exe"
DriverData:"C:\Windows\System32\Drivers\DriverData"
FPS_BROWSER_APP_PROFILE_STRING:"Internet Explorer"
FPS_BROWSER_USER_PROFILE_STRING:"Default"
HOMEDRIVE:"C:"
HOMEPATH:"\Users\aydogan"
IntelliJ IDEA:"C:\Program Files\JetBrains\IntelliJ IDEA 2018.3.5\bin;"
LOCALAPPDATA:"C:\Users\aydogan\AppData\Local"
LOGONSERVER:"\\AYDOGAN"
NUMBER_OF_PROCESSORS:"8"
OneDrive:"C:\Users\aydogan\OneDrive"
OneDriveConsumer:"C:\Users\aydogan\OneDrive"

JWT_KEY seems undefined, I can see it with debug.

I appreciate any help

9
  • Do you use Express.js as well? Also can you share your main js file Commented Aug 19, 2019 at 12:12
  • Check what does ` process.env` console looks like. And shouldn't nodemon config file be nodemon.json Commented Aug 19, 2019 at 12:24
  • I don't use Express.js. It's already nodemon.json, sorry for inconvinience and I add process.env to above @ambianBeing. And thanks a lot for your help. Commented Aug 19, 2019 at 12:48
  • is it working via postman?? Commented Aug 19, 2019 at 12:51
  • Only chechAuth has problem. All other (that I didn't shared) is working well via Postman and Android Studio and React.js. @sultania23 Also chechAuth is working but completely wrong Commented Aug 19, 2019 at 12:55

1 Answer 1

1

You are tying to get the JWT_KEY from environment via "process.env" but you did not set any environment variable for JWT_KEY.

You need to create .env file inside the root of the project and and put JWT_KEY there like JWT_KEY=****** instead of nodemon.js file, also you need to install dotenv package via npm install dotenvand use it inside your main file as

index.js

// Read Environment Variables Config
const dotenv = require('dotenv');
dotenv.config();

...

.env

JWT_KEY=23489sgher8t238ifjk

This way you can get the JWT_KEY via process.env. Also if the repo is public I suggest not to push .env file to repository and keep it local to protect jwt key.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.