Brian Bui
Brian Bui

Reputation: 123

Practical Use of JWT and cookies for Authentication

I am a self taught coder, so I'm relatively new to authentication. I'm trying to store a JWT token into a httpOnly cookie and having a middleware access the cookie to verify that it is currently the user who is trying to reach the profile page.

After I log in I check the networks tab and I do see the cookie set in the header, but after I try redirecting myself into the profile page, it says the cookie is undefined. Can someone tell me what I am doing wrong, and why the cookie isnt carrying over to the next route?

Login

app.post('/users/login', async (req, res) => {
    const { email, password } = req.body;

    try {
        const foundUser = await User.findOne({ email });
        if (!foundUser) return res.status(404).send('User has not been found');

        const validPassword = await bcrypt.compare(password, foundUser.password);

        if (!validPassword) return res.status(400).send('Invalid email or password');

        const token = await foundUser.generateToken();

        // res.header('x-auth-token', token); //stores in local storage
        res.cookie("jwt", token, { secure: true, httpOnly: true });


        res.status(200).redirect('/users/profile')
    } catch (err) {
        res.send(err);
    }
})

Middleware Authentication

const authToken = async (req, res, next) => {
    // const token = req.header('x-auth-token');
    const token = req.cookies.jwt;
    console.log(token);

    if (!token) return res.status(401).send('Please sign in to conintue.');

    try {
        const decodeUser = jwt.verify(token, "secrettunnel");
        const user = await User.findById({ _id: decodeUser._id });

        req.user = user;
        next();
    } catch (err) {
        res.status(400).send('Invalid Token');
    }
}

Protected Route

app.get('/users/profile', auth, (req, res) => {
    res.render('profile');
})

Upvotes: 0

Views: 139

Answers (1)

Deepak Champatiray
Deepak Champatiray

Reputation: 121

Please verify that you have "cookie-parser" in your expressjs application.

var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())

Upvotes: 1

Related Questions