1

I am trying to do my own site (express, html, css) with authentication but can't figure out how to set and receive tokens from headers. So far, in the tutorial I have followed I manually set the bearer tokens in Postman and received it like this

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '')
        const decoded = jwt.verify(token, 'thisismynewcourse')
        const user = await User.findOne({
            _id: decoded._id,
            'tokens.token': token
        })

        if (!user) {
            throw new Error('No user') 
        }

        req.token = token
        req.user = user
        next()
    } catch (e) {
        res.status(401).send({error: 'Unable to authenticate'})
    }
}

How would I achieve this without Postman?

Arseniy
  • 25
  • 1
  • 5

2 Answers2

0

In postman, you can view the code that is actually used to make those calls, in different mainstream languages. I personally found it very useful, and hopefully will solve your problem

enter image description here

0

What you have should work irrespective of what method you use to make the request, so you shouldn't need to change any code.

For example, using CURL, you could run: curl -H 'Authorization: Bearer <token>' http://localhost:8080 and get the same response as you would in Postman. Of course, you'll need to replace the <token> with your token and use the correct URL.

A good guide on Bearer tokens can be found here: What is the OAuth 2.0 Bearer Token exactly?, while that's specifically about OAuth tokens, the principle is essentially the same.