JonasLevin
JonasLevin

Reputation: 2109

How can I access the credentials on the server-side with HTTPOnly?

I send the JWT token as an HTTPonly Cookie from my React app to my express Server to authorize the user.
The token is being sent in the request header but I can't access it in the server middleware.

enter image description here

This is the middleware that is supposed to handle to authorization but I can't access the accessToken from the header and get the response status 403.

const jwt = require("jsonwebtoken");
require("dotenv").config();

module.exports = function(req, res, next) {
  // Get token from header
  const token = req.header('accessToken');

  // Check if no token
  if (!token) {
    return res.status(403).json({ msg: "authorization denied" });
  }

  // Verify token
  try {
    //it is going to give use the user id (user:{id: user.id})
    const verify = jwt.verify(token, process.env.jwtSecret);

    req.user = verify.user;
    next();
  } catch (err) {
    res.status(401).json({ msg: "Token is not valid" });
  }
};

I use cors and also set the credentials to true and the origin to my web-app.

app.use(cors({origin: 'http://localhost:3001', credentials: true }));

This is the important part of my routes:

const express = require('express');
const authorize = require('../middleware/authorize')

const router = express.Router();

router.get("/verify", authorize, (req, res) => {
    try {
      res.json(true);
    } catch (err) {
      console.error(err.message);
      res.status(500).send("Server error");
    }
  });

module.exports = router

And this is my express.js server:

'use strict';
require('dotenv').config();
const mongoose = require('mongoose')
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const cookieParser = require('cookie-parser');

//Import Routes
const userRoute = require('./routes/user')

app.use(cors({origin: 'http://localhost:3001', credentials: true }));
app.use(bodyParser.json());
app.use(cookieParser())
app.use('/account', userRoute);

//connect to db
mongoose.connect(
    process.env.DB_CONNECTION, 
    {
        useUnifiedTopology: true,
        useNewUrlParser: true
    },
    () => console.log('connected to db!')
);

app.listen(3000, ()=>{
    console.log("***********************************");
    console.log("API server listening at localhost:3000");
    console.log("***********************************");
  });

Thanks in advance and I appreciate the effort.

Upvotes: 0

Views: 317

Answers (1)

Nick
Nick

Reputation: 16596

Your httpOnly cookie is being sent back and forward as cookies not as their own headers! Since you already have the cookie-parser middleware, you should be able to grab the access token like this:

const token = req.cookies.accessToken;

Upvotes: 1

Related Questions