KGraber
KGraber

Reputation: 223

Once I have generated a JSON Web Token how do I use it? (Node.js)

I'm building an app with Node.js + Express, and I'm trying to use JSON Web Tokens for authentication. Right now I am at the point where once a valid username/password is entered, the server responds by sending the client a JWT.

This is where I get lost.

How do I send that token along with further requests to the server?

How can I send it as a header?

Upvotes: 3

Views: 885

Answers (3)

Ace
Ace

Reputation: 59

first you need to set the json token in client by using http cookie (res.cookie("token","yourtoken")) or using session

when user sends a request you need to send the token to server.you can read cookie by using req.cookie.token and verify it in middleware or use session

Upvotes: 1

Harpreet Singh
Harpreet Singh

Reputation: 2671

How do I send that token along with further requests to the server?

  1. You can append in your req URL as query parameter. Eg:

http://localhost:8080/api/users?token=tokenValue

  1. You can save it in cookies and when you req a URL, it will fetch up this cookie containing your token. Use document.cookie to save token in your cookie

How can I send it as a header?

Using JQuery

$.ajax({
    type:"POST",
    beforeSend: function (request)
    {
        request.setRequestHeader("Authority", authorizationToken);
    },
    url: "entities",
    data: "",
    success: function(msg) {
    }
});

At Server Side, you can do:

var token = req.body.token || req.query.token || req.headers['x-access-token'];

For Cookie Parsing, you can use: Cookie-Parser

var app = express()
app.use(cookieParser())

app.get('/', function(req, res) {
  console.log("Cookies: ", req.cookies)
})

Further Reading: https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

Upvotes: 2

Nivesh
Nivesh

Reputation: 2603

client can set the access token either as header or query parameter or in request body. Following is a way to send via header:

$.ajax({
    url: 'foo/bar',
    headers: { 'x-access-token': 'some value' },
    data: {}
}).done(function(result){
   //do something
});

Best practice is to save the access-token in browser local storage rather than in cookie. Once you obtain the token once logged it.

Server, best way to include a authentication middleware above all secured routes, where token is required.

auth.middleware:

'use strict';

module.exports = function(req,res,next){
    const jwt = require('jsonwebtoken');
    const config = require('../config/config');

    // check header or url parameters or post parameters for token
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    // decode token
    if (token) {

        // verifies secret and checks exp
        jwt.verify(token, config.secret, function(err, decoded) {           
            if (err) {
                return res.status(401).json({ success: false, message: 'Failed to authenticate token.' });      
            } else {
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;  
                next();
            }
        });

    } else {

        // if there is no token
        // return an error
        return res.status(403).send({ 
            success: false, 
            message: 'No token provided.'
        });

    }

};

routes:

//no token required
app.post('/signup',users.create);

app.post('/login',users.authenticate);

const auth = require('../middleware/auth.middleware');
//token required for below routes
app.use(auth);    
app.get('/info',index.getInfo);

Upvotes: 1

Related Questions