DEV Community 👩‍💻👨‍💻

mahmoud samir
mahmoud samir

Posted on

I have an issue in the auhtentication with jwt

this is not the first time but i don't know why the jsonwebtoken doesn't work with first application i tried alot to reach some page that nead a specific token to reach when and i accessed to this token so when tried to reach this page it tells me no provided token ,
iam sure that my code is completely right and i asked on stack overflow and no one answers this time i tried something different which is passport-jwt and still the autherization not working which it's code is :

const express = require("express") ;
const router = express.Router() ;
const bcrypt = require ("bcryptjs")
const passport = require("passport") ;
const passportJwt = require("passport-jwt")
const jwt = require ("jsonwebtoken") ;

const User = require("../models/userModel.js")
require("../config/passport.js")(passport)
//register

router.post("/signup" , (req ,res)=>{

  let newUser = new User({
    name : req.body.name,
    email:req.body.email ,
    password:req.body.password
  })
  User.addUser(newUser , (err , user)=>{
    if (err){
      res.json({success:false , msg:"failed to register"+err})
    }else {
      res.json({success:true , msg:"register is done"})
    }
  })
})
router.post("/authenticate" , (req ,res)=>{
  let email = req.body.email ;
  let password = req.body.password ;

  User.getUserByEmail(email , (err , user)=>{
    if(err)throw err
    if(!user){
      return res.send({success:false , msg:"this email is not exist"})
    }else{
      User.comparePassword(password , user.password , (err , isMatch)=>{
        if (err) throw err ;
        if(isMatch){
          const token = jwt.sign({id:user._id} , "hello secret" )
          res.json({
            success:true ,
            token:"JWT "+token ,
            user:{
              id:user._id ,
              name:user.name,
            }
          })
        }else{
          res.send({success:false , })
        }
      })
    }
  })

})
router.get("/profile",passport.authenticate('jwt' , {session:false}) , (req ,res,next)=>{
  res.send("here's your profile")
})


module.exports = router ;
Enter fullscreen mode Exit fullscreen mode

this is the code of the route which is called userRoute.js
and the code of the passport.js file is :

const JwtStrategy = require('passport-jwt').Strategy;
const  ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require ("../models/userModel.js")

module.exports = function(passport){
let opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'hello secret';
opts.issuer = 'accounts.examplesoft.com';
opts.audience = 'yoursite.net';
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    User.findOne({id: jwt_payload.sub}, function(err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            return done(null, user);
        } else {
            return done(null, false);
            // or you could create a new account
        }
    });
}));
}

Enter fullscreen mode Exit fullscreen mode

and here's the app.js file :

const express = require("express") ;
const path = require ("path") ;
const bodyParser = require ("body-parser") ;
const passport = require("passport") ;
const cors = require("cors")
const mongoose = require("mongoose") ;
const userRoute = require("./routes/userRoute.js")
const config = require("./config/dbConfig.js")
var session = require('express-session');
const app = express() ;

//connecting to the database
mongoose.connect(config.database)
mongoose.connection.on('connected' ,  ()=>{
  console.log("hello world")
})
//port number

const port = 3000 ;
//cors
app.use(session({ secret: 'hello secret' }));
app.use(cors()) ;
//set static folder
app.use(express.static(path.join(__dirname , "Notes-master")));
//body parser
app.use(bodyParser.json()) ;

//using data from routes
app.use(passport.initialize());
app.use(passport.session());
require("./config/passport")(passport);
app.use(userRoute)

app.get("/", (req , res)=>{
  res.send("here's home")
})
// passport authentication
//server listening

app.listen(port , ()=>{
  console.log(`server started on a port ${port}`)
}) ;

Enter fullscreen mode Exit fullscreen mode

this problem wasted my time alot please help me to solve it .

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.