1 year ago

#304801

test-img

Hazem Ben Abdelhafidh

req.cookies returns [Object: null prototype] {}

I'm trying to implement authentication with jwt in nodejs where I send the accessToken in the response and the refreshToken a httpOnly and I have a route to help me "refresh the Token" .

this is the code for refreshing Token:

exports.refreshToken = catchAsync(async (req, res, next) => {
  const cookies = req.cookies;
  console.log(cookies);
  if (!cookies?.jwt)
   return next(new AppError("you need to connect first", 401));
  const refreshToken = cookies.jwt;
  const foundUser = await User.findOne({ refreshToken }).exec();
  jwt.verify(refreshToken, process.env.REFRESH_TOKEN, (err, decoded) => {
  if (err || foundUser.id !== decoded.id)
  return next(new AppError("who are you?", 403));
  const accessToken = jwt.sign(
  {
    id: decoded.id,
  },
  process.env.ACCESS_TOKEN,
  { expiresIn: "15d" }
);
  res.json({ accessToken });
});
});

so the problem is that I'm not recieving the cookie with the request so I can't "refresh" the current token and I have no idea why this is happening even though it was working just fine and I didn't change anything...

this is the app.js code where I set up everything

    const dotenv = require("dotenv");
dotenv.config();
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const rateLimit = require("express-rate-limit");
const mongoSanitize = require("express-mongo-sanitize");
const cookieParser= require('cookie-parser');
const xss = require("xss-clean");
const userRouter = require("./routes/userRoutes");
const postRouter = require("./routes/postRoutes");
const commentRouter = require("./routes/commentRoutes.js");
const helmet = require("helmet");
const globalErrorHandler = require("./controllers/errorController");
process.on("uncaughtException", (err) => {
  console.log(err.name);
  console.log(err.message);
  console.log("shutting down...");
  process.exit(1);
});
const AppError = require("./utils/appError");
const hpp = require("hpp");


const port = 5000;
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
const corsOptions = {
  origin: "http://localhost:3000",
  credentials: true,
};


app.use(cors(corsOptions));
app.use(mongoSanitize());
app.use(xss());
app.use(hpp());
app.use(cookieParser());

const limiter = rateLimit({
  max: 100,
  windowMs: 60 * 60 * 1000,
  message: "too many requests please try again in an hour",
});
app.use(helmet());
app.use("", limiter);

const URL = process.env.DATABASE_URL;
mongoose
  .connect(URL, {
    useNewUrlParser: true,
    useCreateIndex:true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("connected!"));
app.listen(port, () => console.log(`App running on port ${port}`));

app.use('/users',userRouter);

app.all("*", (req, res, next) => {
  next(new AppError(`can't find ${req.originalUrl} on this server`, 404));
});

app.use(globalErrorHandler);

Edit:

this is the login function where I send the cookies:

exports.login = catchAsync(async (req, res, next) => {
  const { email, password } = req.body;
  const user = await User.findOne({ email }).select("+password").exec();
  if (!user || !user.correctPassword(password, user.password)) {
    return next(new AppError("Credentials are wrong", 404));
  }
  const accessToken = jwt.sign({ id: user.id }, process.env.ACCESS_TOKEN, {
    expiresIn: "15d",
  });
  const refreshToken = jwt.sign(
    { name: user.name },
    process.env.REFRESH_TOKEN,
    {
      expiresIn: "60d",
    }
  );
  user.refreshToken = refreshToken;
  await user.save();
  user.refreshToken = undefined;
  res.cookie("jwt", refreshToken, {
    httpOnly: true,
    sameSite: "None",
    secure: true,
    expires: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
  });
  res.status(200).json({
    status: "success",
    accessToken,
    data: { user },
  });
});

javascript

node.js

express

httponly

0 Answers

Your Answer

Accepted video resources