0
votes

I am using JWT in my node.js app. Everything with token works fine. I can get a token when I have logged in.

Here's how I check user auth.:

const jwt = require('jsonwebtoken')

try{
    const token = req.headers.authorization
    const decoded = jwt.verify(token, 'secret')
    req.userData = decoded
    next()
}
catch(err){
    return res.send("Auth error")
}

I can access protected routes if I change token value with that token I've got after log in.

But I want to save the token (on user's side???), and each time when the user tries to access protected routes (from frontend), send token as req.headers.authorization, so that the token can be verified, and the user can access the route.

So, how to save and later send the token, that has been generated after user's log in each time when protected routes are linked to?

Thank you.

(I am not using any javascript frontend frameworks)

2

2 Answers

0
votes

Common approach to save it to a local storage. Just keep in mind local storage size and other limitations in different browsers.

0
votes

If it's a token for authentication, you can use a httpOnly cookie to prevent XSS attacks, which is a risk with local storage.

To save a JWT in a cookie in express:

const accessToken = jwt.sign(); 

return res
    .status(201)
    .cookie("accessToken", accessToken, {
        httpOnly: true,
        maxAge: (1000*60*5), // 5m
        secure: true,
        signed: true
    })
    .end();

When getting from requests:

const { accessToken } = req.signedCookies;

Inside your app.js:

const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();

app.use(cookieParser("secret"));

With httpOnly cookies your requests automatically send the cookie along with the request (only if the cookie belongs to the same domain). Just make sure your CORS and http client are properly configured to handle the cookie