简体   繁体   中英

JWT using signed-cookies to access JWT token from front-end

I am (for the life of me) trying to create a login using JWT tokens. I have been working on this for days and am having a really hard time.

Here is where I am at so far.

Login Request | Confirms the username and password are correct, creates a json web token and attaches it to a http-only signed cookie. The use data is then sent to the frontend via json. I can successfully access the user data from the json response on the front end.

const loginUser = async (req, res, next) => {
    try {
        const {username, password} = req.body
        //grabbing user associated with our username
        const user = await User.findOne({username:username}) 
        //check if username and password come from the same user
        if (user && (await bcrypt.compare(password, user.password))){
            const token = generateToken(user._id) //creating a jwt token
            //creating a cookie with our token in it
            res.cookie('token', token, {
                maxAge: 1000*60*15,
                httpOnly: true,
                signed: true
            })
            console.log(req.signedCookies)
            //sending our user info to frontend via json
            res.status(200).json({
                _id: user._id,
                name: user.username,
                email: user.email,
            })
        } else {
            res.status(400)
            throw new Error('Invalid credentials')
        }
    } catch (error) {
        next(error)
    }
}

Front-end Login | The login form works and I successfully get the json data no problem. I could also attach the token to the json data if needed and I understand how to do that.

<h1>Login</h1>
<form id="login_form">
    <label for="username">Username</label>
    <input type="text" name="username">
    <label for="password">Password</label>
    <input type="password" for="password" name="password">
    <button type="button" onclick="loginSubmit()">Submit</button>
</form>

<script>
    const loginSubmit = async () => {
        const loginForm = document.getElementById('login_form') //grabbing the login_form
        const data = new URLSearchParams() // this can take in form data
        //this for loop runs for each input field for the form passed into FormData()
        for (const pair of new FormData(loginForm)){
            data.append(pair[0], pair[1]) //pair[0] is the name of the input, pair[1] is the value
        }
        const response = await fetch('/user/login', {
            method: 'POST',
            body: data //passing the form data into our req.body
        })
    }
</script>

My question is now what? I have confirmed the cookie is being sent on each request and is in my developer console. I just don't understand the next step I need to take to authenticate the user on each request. I think I understand logout functionality. I could just rewrite over the token value and make it an arbitrary string. But I do not understand how to verify the information in the cookie from the front end of maybe I just do not understand the process as a whole.

Any help would be so wonderful. Thank you for your time!

A common way to use JWT tokens is to verify each user request by creating an authentication middleware that verifies the token each time a request is sent to a protected route.

For example

var cookieParser = require('cookie-parser');

app.use(cookieParser());

const auth = async (req, res, next) => {
  try {
    token = req.signedCookies.token;
    if (token) {
      res.locals.decodedData = jwt.verify(token, JWT_SECRET);
      next();
    } else {
        res.status(401).json({message: 'not logged in'});
    }
  } catch (error) {
    // jwt.verify() throws an error if the token is invalid
    res.status(401).json({message: 'invalid token'});
    console.log(error);
  }
};

app.get('/super/secret/files', auth, givefiles); 

Here the next() function is only called once the token has been verified meaning the giveFiles function used in the /super/secret/files route will never be run for an unauthenticated user.

You can also make every route under a certain route protected by doing this:

app.use('/secret', auth);
app.get('/secret/file1', giveFile1);
app.get('/secret/file2', giveFile2);

This automatically applies the auth middleware to all paths under the /secret route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM