0

I saw many tutorials on jwt authentication but every video maker uses Postman to show what's happening and they pass on the header in the headers section while requesting a URL in Postman. I tried to do it with JavaScript but I was not able to do it.

I want to do jwt authentication but after token generation, I send it to client side to use it for further requests but I failed to do so after trying it a few times. I also tried to set req.headers in server side but it didn't do what I wanted to..

I want to set request headers for authentication of the form "Bearer {token}" for every request after token generation. How to do it with JS??

What I am most concerned about is that every tutorial does it with postman but they didn't show how they implemented it in their own app. I hope my question is clear.

2
  • Are you trying to make http requests or want you to secure routes on a server with JWTs ? Commented Mar 29, 2020 at 20:41
  • Actually want to send headers to access secure routes Commented Jun 27, 2020 at 19:10

5 Answers 5

2

You can easily add header on your http request like that

it has been solved here Node.JS: How to send headers with form data using request module

Sign up to request clarification or add additional context in comments.

2 Comments

fetch does not exists in nodejs
I wanted to send headers through client on request..so fetch was always an option
1

In vanilla nodejs:

const uri = "http://example.com";

const options = {
    headers: {
        "Authorization": "Bearer ...."
    }
}

// require http/https lib
let req = require("http").request(uri, options, (res) => {

    const chunks = [];

    res.on("data", function (chunk) {
        chunks.push(chunk);
    });


    res.once("end", () => {

        // concat body chunks
        let body = Buffer.concat(chunks);
        console.log(body.toString());

    });


});

req.on("error", (err) => {
    console.log(err);
});

req.end();

https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_options_callback

Comments

0

Something like that:

$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("custom_header", "value");
  },
  success: function(data) {
  }
});

1 Comment

1) thats use jQuery and is not plain JS, 2) OP asked specific for node
0

First install jwt and express framework using npm then make a middleware file which will check if the tokek is set or not.

Middleware.js :

let jwt = require('jsonwebtoken');
const config = require('./config.js');

let checkToken = (req, res, next) => {
    let token = req.headers['authorization']; // Express headers are auto converted to lowercase

    if (token) {
        if (token.startsWith('Bearer ')) {  // Checks if it contains Bearer
            // Remove Bearer from string
            token = token.slice(7, token.length); //Separate Bearer and get token
        }

        jwt.verify(token, config.secret, (err, decoded) => {  //Inser the token and verify it.
            if (err) {
                return res.json({
                    status: false,
                    message: 'Token is not valid'
                });
            } else {
                req.decoded = decoded;
                next();
            }
        });
    } else {
        return res.json({
            status: false,
            message: 'Access denied! No token provided.'
        });
    }
};

Next, create a config file which will contain the secrets.

Config js:

module.exports = {
    secret: 'worldisfullofdevelopers'
};

Finally, create a token route which will create your token and after that the rest of the calls will be authenticated for that token.

Index.js :

const middleware = require('./middleware');
const jwt = require("jsonwebtoken");
const config = require('./config.js');

//Call token Route
app.use('/token', (req, res, next) => {

    //Generate Token
    let token = jwt.sign({ username: "test" },
        config.secret,
        {
            expiresIn: '1h' // expires in 1 hours
        }
    );

    //Send Token
    res.json({
        success: true,
        message: 'Authentication successful!',
        token: token
    });

});

//Add Authentication to all routes
app.use(middleware.checkToken);

//===> All the routes after middleware will be checked for token

app.use('/getUser', (req, res, next) => {; 
 console.log('do something')
});

4 Comments

How did you set the header Authorization with the token generated (that you responded with in json)?
whats your frontend framework? or do yo want to set it with backend nodejs
I was using vanilla JS for that project particularly
You can set it from frontend using ajax
0

If I understand correctly, you want to set the HTTP header on the client, in order to pass an authentication token to the server. I would recommend that you use a library like **axios*.

Using axios, once you receive the toke, set the header for every outgoing communication with the following line of code:

axios.defaults.headers.common['Authorization'] = "Bearer " + token;

This will set the authentication http header to the form you need.

1 Comment

I tried doing this after the token was generated but was unable to see headers when request was made again..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.