i try to make a Loginsystem with a JSON Webtoken. The token is stored in a cookie. The login works fine, the token is set on the client side, but if i try to validate the token in the backend to get the user information from the database, the cookie returns as undefined.
I assume it has something to do with the order of the commands in the main file of the backend, but i cannot figure out, whats wrong with it.
Thats the main file:
const express = require("express"),
cookieParser = require("cookie-parser"),
mongoose = require("mongoose"),
bcrypt = require("bcrypt"),
Joi = require("joi"),
rssParser = require("rss-parser"),
cors = require("cors"),
jwt = require("jsonwebtoken"),
verify = require("./VerifyToken"),
authRoute = require("./Auth")
app = express()
parser = new rssParser()
app.use(cookieParser())
app.use(express.urlencoded({extended: false}))
app.use(express.json());
app.use("/api/user", authRoute)
app.use(cors({
origin:"http://localhost:3000",
credentials: true,
optionsSuccessStatus:200
}))
require("dotenv").config()
mongoose.connect(process.env.DB_CONNECTION, {
useNewUrlParser: true,
useUnifiedTopology: true
},() => {
console.log("Status: Mongoose: Connected (Test Database)")
})
const jwt = require("jsonwebtoken")
const cookieParser = require("cookie-parser")
module.exports = function (req, res, next){
const token = req.cookies.authToken;
console.log(token)
if(!token){
console.log("No Token found")
res.status(400).send("Access denied")
}
else{
try{
const verified = jwt.verify(token, process.env.TOKEN_SECRET);
req.user = verified
console.log("Token verified: " + req.user._id)
next()
}
catch{
res.status(400).send("invalid token")
}
}
}