jwt.verify函数不返回任何内容,并且api无法获得任何响应

时间:2019-02-18 08:50:13

标签: node.js express jwt

App.js文件

const express = require('express');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');
const { buildSchema } = require('graphql');
const isAuth =  require('./middleware/is-auth');
var mysql      = require('mysql');

const app = express();
const jwt = require('jsonwebtoken'); 

var connection = mysql.createConnection({
host     : 'localhost', //mysql database host name
user     : 'root', //mysql database user name
password : '', //mysql database password
database : 'test' //mysql database name
});

connection.connect(function(err) {
if (err) throw err
console.log('You are now connected with mysql database...')
})


app.use(bodyParser.json());

app.use(isAuth);

app.use(
 '/graphql',
   graphqlHttp({
    schema: buildSchema(`
       type users {
         id: String!
         username: String!
         password: String!
         role: String!
         name: String!
         photo: String!
        }
       type AuthData
       {
      userID: String!
      token: String!
      tokenExpiration: Int!
    }
    type RootQuery {
        getUsers: [users!]!
        login(username: String!, password:  String!): AuthData! 
    }
    type RootMutation {
      createUsers(name: String): String
    }
    schema {
        query: RootQuery
        mutation: RootMutation
    }
`),
rootValue: {
  login: async ({username,password}) =>  {




    return new Promise((resolve, reject) => {
      connection.query('select * from users where username = "'+username+'"', (error, results, fields) => {
        if (error) {
          reject(error)
        } else {
          resolve(results);
        }
      })
    }).then(function(result) {
      const users =  result;

    if(!users || users[0] == null)
    {
      throw new Error('User does not exist')
    }
    const token = jwt.sign({userID: users[0]['id'], username: users[0]['username']}, 'SomeSuperSecretKey', {
       expiresIn: '1h'
    });
    return { userID: users[0]['id'], token, token,tokenExpiration: 1}
  })
  },
  getUsers: async (req) => {

    if(!req.isAuth)
    {
      throw new Error('Unauthenticated');
    }
    // Note, we have to return the Promise here
    return new Promise((resolve, reject) => {
      connection.query('select * from users', (error, results, fields) => {
        if (error) {
          reject(error)
        } else {
          // Don't stringify
          resolve(results)
        }
      })
    })
  },

},
graphiql: true
})
);

app.listen(3000);

is-auth.js文件

const jwt  = require ('jsonwebtoken');

module.exports = (req, res, next) => {
   const authHeader = req.get('Authorization');
   if(!authHeader){
      console.log("Here");
      req.isAuth = false;
      return next();
    }
   const token = authHeader.split(' ')[1]; // bearer tokenValue 

   if(!token || token === ''){
      console.log("Here1");
      req.authHeader = false;
      return next();
   }

   let decodedToken;
   try
   {
      console.log(token);
      decodedToken = jwt.verify(token, 'SomeSuperSecretKey'); //same key used in app.js

   }catch(err){
      console.log(err);
      req.isAuth = false;
      return next(); 
   }

  if(!decodedToken){
      req.isAuth = true;
      req.userID = decodedToken.userID;
      return next(); 
  }

}

Post man Api

jwt.verify函数不会返回卡住的任何东西,并且api不会响应。因此问题出在校验函数中,它卡在其中了。而且,如果我输入自己的自定义令牌,则会出现另一个错误,表明不允许您输入自己的自定义令牌,可以使用jlt生成的令牌。

0 个答案:

没有答案